更新时间:2023-10-22 14:05:52
虽然这个问题和问题很相似:如何在数据框的某些行的所有列上使用pandas应用函数
Although this question is very similar to the question: How to use pandas apply function on all columns of some rows of data frame
我认为这里值得展示几个方法,在一行中使用 np.where
和从 isin
、isin
生成的布尔掩码> 将返回一个布尔系列,其中任何行都包含列表中的任何匹配项:
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
这里使用 2 个 loc
语句并使用 ~
反转掩码:
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