为什么 Pandas 给出 AttributeError: 'SeriesGroupBy' 对象没有属性 'pct'?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52642351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why Pandas gives AttributeError: 'SeriesGroupBy' object has no attribute 'pct'?
提问by Franco Piccolo
I'm trying to pass a user defined function pct
to Pandas agg
method, and it works if I only pass that function but it doesn't when I use the dictionary format for defining the functions. Does anyone know why?
我正在尝试将用户定义的函数传递pct
给 Pandasagg
方法,如果我只传递该函数,它会起作用,但当我使用字典格式定义函数时则不会。有谁知道为什么?
import pandas as pd
df = 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)
returns as expected
按预期返回
B C
A
1 0.333333 0.333333
4 0.333333 0.333333
7 0.333333 0.333333
But
但
aggs = {'B':['pct']}
df.groupby('A').agg(aggs)
returns the following error:
返回以下错误:
AttributeError: 'SeriesGroupBy' object has no attribute 'pct'
回答by jezrael
There is string 'pct'
, need variable pct
- lambda function by removing ''
:
有字符串'pct'
,需要pct
通过删除变量- lambda 函数''
:
aggs = {'B':pct}
print(df.groupby('A').agg(aggs))
B
A
1 0.333333
4 0.333333
7 0.333333