我有两个列表
A = ['a','b','c','d','e']
B = ['c','e']
带有列的数据框
A
0 a
1 b
2 c
3 d
4 e
我希望为 B 中的元素与 A 匹配的行创建一个附加列。
A M
0 a
1 b
2 c match
3 d
4 e match
最佳答案
您可以使用loc
或numpy.where
和条件 isin
:
df.loc[df.A.isin(B), 'M'] = 'match'
print (df)
A M
0 a NaN
1 b NaN
2 c match
3 d NaN
4 e match
或者:
df['M'] = np.where(df.A.isin(B),'match','')
print (df)
A M
0 a
1 b
2 c match
3 d
4 e match
关于python - 根据条件在数据框 pandas 中创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672958/