请帮我解决这个问题。我在网上搜索,但找不到解决方案。
df
Id Fruit
1 Apple
1 Carrot
2 Apple
3 Carrot
list = [fruit, vegetable, both]
问题是,如果ID的水果列包含苹果或胡萝卜,该如何分配每个ID。如果id包含苹果,则为ID 1分配水果,如果仅是胡萝卜,则分配蔬菜,如果两者都都分配。
我试图按行使用str.contains,但是它没有ID列。
结果
Newdf
Id Fruit New_col
1 Apple Both
1 Carrot Both
2 Apple Fruit
3 Carrot Vegetable
十分感谢。
这样做map
第一,然后我们只用transform
nunqiue
找到的位置应该是“既”
s=df.Fruit.map({'Apple':'Fruit','Carrot':'Vegetable'})
mask=s.groupby(df.Id).transform('nunique').eq(2)
s[mask]='both'
df['New']=s
df
Out[190]:
Id Fruit New
0 1 Apple both
1 1 Carrot both
2 2 Apple Fruit
3 3 Carrot Vegetable
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句