Dataframe聚合方法传递列表问题

Sco*_*ton 5 python aggregate pandas

这可能是一个错误,但是您对此 pandas 功能有何看法:

df = pd.DataFrame(np.arange(20).reshape(10,-1), columns=[*'AB'])

def f(x):
    print(type(x))

df.agg(f)
Run Code Online (Sandbox Code Playgroud)

输出:

<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
A    None
B    None
dtype: object
Run Code Online (Sandbox Code Playgroud)

但是,如果我将 agg 方法中的函数调用包装在括号中,将单个函数作为列表传递。

df = pd.DataFrame(np.arange(20).reshape(10,-1), columns=[*'AB'])

def f(x):
    print(type(x))


df.agg([f])
Run Code Online (Sandbox Code Playgroud)

输出:

<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
      A     B
      f     f
0  None  None
1  None  None
2  None  None
3  None  None
4  None  None
5  None  None
6  None  None
7  None  None
8  None  None
9  None  None
Run Code Online (Sandbox Code Playgroud)

所做的一切更改是将自定义函数作为单个值列表传递。

jto*_*lem 0

在您的情况下,您应该考虑使用apply而不是agg因为您的函数不执行多个值的聚合。