我正在尝试将用户定义的函数传递pct给 Pandasagg方法,如果我只传递该函数,它会起作用,但当我使用字典格式定义函数时,它不会。有谁知道为什么?import pandas as pddf = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['A', 'B', 'C'])pct = lambda x: len(x)/len(df)df.groupby('A').agg(pct)按预期返回 B CA 1 0.333333 0.3333334 0.333333 0.3333337 0.333333 0.333333但aggs = {'B':['pct']}df.groupby('A').agg(aggs)返回以下错误:AttributeError: 'SeriesGroupBy' object has no attribute 'pct'
1 回答

子衿沉夜
TA贡献1828条经验 获得超3个赞
有字符串'pct',需要pct通过删除变量- lambda 函数'':
aggs = {'B':pct}
print(df.groupby('A').agg(aggs))
B
A
1 0.333333
4 0.333333
7 0.333333
添加回答
举报
0/150
提交
取消