我有一个pandas数据帧,我想按组汇总,使用一个解析为布尔值的自定义函数.
考虑以下数据.df
描述了4个人,每个人都喜欢水果.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["danny", "danny", "danny", "monica", "monica", "monica", "fred", "fred", "sam", "sam"],
"fruit": ["apricot", "apple", "orange", "apricot", "banana", "watermelon", "apple", "apricot", "apricot", "peach"]
})
print(df)
## name fruit
## 0 danny apricot
## 1 danny apple
## 2 danny orange
## 3 monica apricot
## 4 monica banana
## 5 monica watermelon
## 6 fred apple
## 7 fred apricot
## 8 sam apricot
## 9 sam peach
我想总结一下这张表,找出喜欢102 apricot
and apple
的人.换句话说,我的desired output是下表
# desired output
## name fruit
## 0 danny True
## 1 monica False
## 2 fred True
## 3 sam False
My attempt
我首先定义了一个函数,用于搜索目标列表中是否存在字符串:
def is_needle_in_haystack(needle, haystack):
return all(x in haystack for x in needle)
is_needle_in_haystack()
个有效示例:
is_needle_in_haystack(["zebra", "lion"], ["whale", "lion", "dog"])
# False
is_needle_in_haystack(["rabbit", "cat"], ["hamster", "cat", "monkey", "rabbit"])
# True
现在我使用is_needle_in_haystack()
,将df
按name
分组:
target_fruits = ["apricot", "apple"]
df.groupby(df["name"]).agg({"fruit": lambda x: is_needle_in_haystack(target_fruits, x)})
那么为什么我会得到下面的输出,这显然不是预期的?
## fruit
## name
## danny False
## fred False
## monica False
## sam False
我的代码做错了什么?