根据 ID 列的值创建一个新列

请帮我解决这个问题。我在网上搜索,但找不到解决方案。


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 

非常感谢。


守着星空守着你
浏览 161回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python