繁体   English   中英

根据条件在数据框熊猫中创建列

[英]creating a column in dataframe pandas based on a condition

我有两个清单

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

您可以使用locnumpy.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

暂无
暂无

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

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