繁体   English   中英

比较两列具有熊猫字符串列表的列

[英]compare two columns having list of strings in pandas

我在熊猫中有一个数据帧,该数据帧有两列,每一行是一个字符串列表,如何检查唯一行上的这两列中是否有单词匹配(标志列是所需的输出)

A                B            flag

hello,hi,bye     bye, also       1
but, as well     see, pandas     0 

我努力了

df['A'].str.contains(df['B'])

但是我得到这个错误

TypeError: 'Series' objects are mutable, thus they cannot be hashed

您可以通过split和set s将每个值转换为单独的单词,并通过&检查交集,然后将值转换为boolean-将空集转换为False ,最后将其转换为int s- Falses0 s和True s为1 s 。

zipped = zip(df['A'], df['B'])
df['flag'] = [int(bool(set(a.split(',')) & set(b.split(',')))) for a, b in zipped]
print (df)
              A            B  flag
0  hello,hi,bye    bye,also     1
1   but,as well  see,pandas     0

类似的解决方案:

df['flag'] = np.array([set(a.split(',')) & set(b.split(',')) for a, b in zipped]).astype(bool).astype(int)
print (df)
              A            B  flag
0  hello,hi,bye    bye, also     1
1   but,as well  see, pandas     0

编辑:有可能是之前一些空格, ,所以添加mapstr.strip并删除与空字符串filter

df = pd.DataFrame({'A': ['hello,hi,bye', 'but,,,as well'], 
                   'B': ['bye ,,, also', 'see,,,pandas']})
print (df)

               A             B
0   hello,hi,bye  bye ,,, also
1  but,,,as well  see,,,pandas

zipped = zip(df['A'], df['B'])

def setify(x):
    return set(map(str.strip, filter(None, x.split(','))))

df['flag'] = [int(bool(setify(a) & setify(b))) for a, b in zipped]
print (df)
               A             B  flag
0   hello,hi,bye  bye ,,, also     1
1  but,,,as well  see,,,pandas     0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM