如何获得两个熊猫系列文本列的交集?

问题描述 投票:1回答:4

我有两个大熊猫系列文本列,我怎么能得到那些?

print(df)

0  {this, is, good}
1  {this, is, not, good}

print(df1)

0  {this, is}
1  {good, bad}

我正在寻找类似下面的输出。

print(df2)

0  {this, is}
1  {good}

我试过了,但它又回来了

df.apply(lambda x: x.intersection(df1))
TypeError: unhashable type: 'set'
python python-3.x pandas
4个回答
1
投票

看起来像一个简单的逻辑:

s1 = pd.Series([{'this', 'is', 'good'}, {'this', 'is', 'not', 'good'}])
s2 = pd.Series([{'this', 'is'}, {'good', 'bad'}])
s1 - (s1 - s2)  
#Out[122]: 
#0    {this, is}
#1        {good}
#dtype: object

1
投票

这种方法对我有用

import pandas as pd
import numpy as np

data = np.array([{'this', 'is', 'good'},{'this', 'is', 'not', 'good'}])
data1 = np.array([{'this', 'is'},{'good', 'bad'}])
df = pd.Series(data)
df1 = pd.Series(data1)

df2 = pd.Series([df[i] & df1[i] for i in xrange(df.size)])
print(df2)


1
投票

我很欣赏以上答案。如果你有DataFrame,这里有一个简单的例子来解决它(我想,在查看你的变量名如dfdf1之后,你已经问过DataFrame了。)。

这个df.apply(lambda row: row[0].intersection(df1.loc[row.name][0]), axis=1)会这样做。让我们看看我是如何达成解决方案的。

https://stackoverflow.com/questions/266582...的答案对我有帮助。

>>> import pandas as pd

>>> 
>>> df = pd.DataFrame({
...     "set": [{"this", "is", "good"}, {"this", "is", "not", "good"}]
... })
>>> 
>>> df
                     set
0       {this, is, good}
1  {not, this, is, good}
>>> 
>>> df1 = pd.DataFrame({
...     "set": [{"this", "is"}, {"good", "bad"}]
... })
>>> 
>>> df1
           set
0   {this, is}
1  {bad, good}
>>>
>>> df.apply(lambda row: row[0].intersection(df1.loc[row.name][0]), axis=1)
0    {this, is}
1        {good}
dtype: object
>>> 

How I reached to the above solution?

>>> df.apply(lambda x: print(x.name), axis=1)
0
1
0    None
1    None
dtype: object
>>> 
>>> df.loc[0]
set    {this, is, good}
Name: 0, dtype: object
>>> 
>>> df.apply(lambda row: print(row[0]), axis=1)
{'this', 'is', 'good'}
{'not', 'this', 'is', 'good'}
0    None
1    None
dtype: object
>>> 
>>> df.apply(lambda row: print(type(row[0])), axis=1)
<class 'set'>
<class 'set'>
0    None
1    None
dtype: object
>>> df.apply(lambda row: print(type(row[0]), df1.loc[row.name]), axis=1)
<class 'set'> set    {this, is}
Name: 0, dtype: object
<class 'set'> set    {good}
Name: 1, dtype: object
0    None
1    None
dtype: object
>>> df.apply(lambda row: print(type(row[0]), type(df1.loc[row.name])), axis=1)
<class 'set'> <class 'pandas.core.series.Series'>
<class 'set'> <class 'pandas.core.series.Series'>
0    None
1    None
dtype: object
>>> df.apply(lambda row: print(type(row[0]), type(df1.loc[row.name][0])), axis=1)
<class 'set'> <class 'set'>
<class 'set'> <class 'set'>
0    None
1    None
dtype: object
>>> 

0
投票

与上面类似,除非您想将所有内容保存在一个数据帧中

Current df:
df = pd.DataFrame({0: np.array([{'this', 'is', 'good'},{'this', 'is', 'not', 'good'}]), 1: np.array([{'this', 'is'},{'good', 'bad'}])})

Intersection of series 0 & 1
df[2] = df.apply(lambda x: x[0] & x[1], axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.