简体   繁体   English

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

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

I have a data frame in pandas having two columns where each row is a list of strings, how would it be possible to check if there is word match(es) in these two columns on a unique row(flag column is the desired output) 我在熊猫中有一个数据帧,该数据帧有两列,每一行是一个字符串列表,如何检查唯一行上的这两列中是否有单词匹配(标志列是所需的输出)

A                B            flag

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

I have tried 我努力了

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

but I got this error 但是我得到这个错误

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

You can convert each value to separately words by split and set s and check intersection by & , then convert values to boolean - empty sets are converted to False s and last convert it to int s - Falses are 0 s and True s are 1 s. 您可以通过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

Similar solution: 类似的解决方案:

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

EDIT: There is possible some whitespaces before , , so add map with str.strip and also remove empty strings with filter : 编辑:有可能是之前一些空格, ,所以添加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