为什么熊猫给出AttributeError:'SeriesGroupBy'对象没有属性'pct'?

Fra*_*olo 4 python pandas pandas-groupby

我正在尝试将用户定义的函数传递pct给Pandas agg方法,如果我仅传递该函数,则该函数有效,但是当我使用字典格式定义函数时,该函数不起作用。有人知道为什么吗?

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)
Run Code Online (Sandbox Code Playgroud)

预期回报

    B   C
A       
1   0.333333    0.333333
4   0.333333    0.333333
7   0.333333    0.333333
Run Code Online (Sandbox Code Playgroud)

aggs = {'B':['pct']}
df.groupby('A').agg(aggs)
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

AttributeError: 'SeriesGroupBy' object has no attribute 'pct'
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

有字符串'pct',需要pct删除''以下变量-lambda函数:

aggs = {'B':pct}
print(df.groupby('A').agg(aggs))

          B
A          
1  0.333333
4  0.333333
7  0.333333
Run Code Online (Sandbox Code Playgroud)