首页 > 解决方案 > 列包含列

问题描述

我想看看我的数据框列 A 的每一行中是否包含列 B 中的值。

df = pd.DataFrame({'A': ["Is it 54321?", "Is it 4321?", "Is it 321?"],
                   'B': [54321, 54321, 54321]})

我试过:

df["C"] = df["A"] .str .contains(df["B"])

我想:

'C': [1,0,0]

但我得到了:

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

标签: pythonpandascontains

解决方案


或者:

df['C']=df.A.str.contains(r'\b(?:{})\b'.format('|'.join(df.B.astype(str)))).astype(int)
print(df)

              A      B  C
0  Is it 54321?  54321  1
1   Is it 4321?  54321  0
2    Is it 321?  54321  0

推荐阅读