create new pandas dataframe column based on if-else condition with a lookup

六眼飞鱼酱① 提交于 2019-12-02 02:58:41
EdChum

Although this question is very similar to the question: How to use pandas apply function on all columns of some rows of data frame

I think here it's worth showing a couple methods, on a single line using np.where with a boolean mask generated from isin, isin will return a boolean Series where any rows contain any matches in your list:

In [71]:
lookup = ['C','D']
df['result'] = np.where(df['letters'].isin(lookup), 1, 0)
df

Out[71]:
  letters  result
0       A       0
1       B       0
2       C       1
3       D       1
4       E       0
5       F       0

here using 2 loc statements and using ~ to invert the mask:

In [72]:
df.loc[df['letters'].isin(lookup),'result'] = 1
df.loc[~df['letters'].isin(lookup),'result'] = 0
df

Out[72]:
  letters  result
0       A       0
1       B       0
2       C       1
3       D       1
4       E       0
5       F       0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!