【发布时间】:2019-09-03 12:09:20
【问题描述】:
我有一个数据框,其中有一行名为 items,我有一个名为 topitems 的列表。以下是它的一些前任
Df.head()
Item
Toy
Car, Toy
Buses, Car
Bike
Barbie
Lorri
我的清单是顶级项目
[Toy, Bike, Car]
现在我想要数据框中的另一列称为 Top Item。
我尝试过设置和交集,但它们返回两个匹配的值
对玩具,它返回玩具 d 对玩具和汽车它返回玩具和汽车,但我希望它返回唯一的玩具
dff['topitems'] = dff.items.apply(lambda x: list(set(x).intersection(set(topitems))))
我希望结果如下所示,
Df.head()
Item | Top item
Toy | Toy
Car, Toy | Car (note : i don't want the second value even though
it's in my list)
Buses, Car | Car
Bike | Bike
Barbie | Blank
Lorri | Blank
【问题讨论】:
-
也许使用索引 [0] 从列表中获取第一个元素。或者更好的
[:1]在列表为空时跳过错误
标签: python pandas set intersection