我的数据框有一个名为' a'它可能包含' apple'和' orange'。我想要的是在它们存在的情况下提取它们,否则标记“其他人”。
我可以简单地遍历行并提取它们。但是,我看到numpy.where()
用于类似目的的一些用法,但只有两个类别。
result = numpy.where(df['a'].str.contains('apple'), 'apple', 'others')
是否有可能在3个类别的情况下应用它?换句话说,result
应包含' apple',' orange'或'其他'的条目。
有没有比简单循环更好的方法呢?
答案 0 :(得分:3)
只需查找带有apple
mango
或np.in1d
的项目即可创建布尔掩码,然后可以将其与np.where
一起用于将其余部分设置为{ {1}}。因此,我们会 -
others
对于您可能希望使用具有这些名称作为较大字符串一部分的字符串的情况,您可以使用df['b'] = np.where(np.in1d(df.a,['apple','orange']),df.a,'others')
(从@jezrael's solution
抓住这个想法,我希望没关系!)和然后使用str.extract
,就像这样 -
np.where
示例运行 -
strings = df.a.str.extract('(orange|apple)')
df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')
答案 1 :(得分:2)
df = pd.DataFrame({'a': ['orange','apple','a']})
print (df)
a
0 orange
1 apple
2 a
df['new'] = df.a.str.extract('(orange|apple)', expand=False).fillna('others')
print (df)
a new
0 orange orange
1 apple apple
2 a others