只需使用np.in1d 查找apple 或mango 的项目即可创建一个布尔掩码,然后可以将其与np.where 一起使用以将其余项目设置为others。因此,我们会有 -
df['b'] = np.where(np.in1d(df.a,['apple','orange']),df.a,'others')
如果您可能希望使用将这些名称作为较大字符串的一部分的字符串,您可以使用str.extract(从@jezrael's solution 获得这个想法,我希望没关系!)然后使用@987654330 @,就像这样 -
strings = df.a.str.extract('(orange|apple)')
df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')
示例运行 -
In [294]: df
Out[294]:
a
0 apple-shake
1 orange
2 apple-juice
3 apple
4 mango
5 orange
6 banana
In [295]: strings = df.a.str.extract('(orange|apple)')
In [296]: df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')
In [297]: df
Out[297]:
a b
0 apple-shake apple
1 orange orange
2 apple-juice apple
3 apple apple
4 mango others
5 orange orange
6 banana others