根据条件在数据帧pandas中创建列

时间:2017-04-28 05:55:38

标签: python list pandas dataframe

我有两个列表

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

1 个答案:

答案 0 :(得分:3)

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