python-3.x - pandas groupby apply 不会广播到 DataFrame

标签 python-3.x pandas

使用 Pandas 0.19.0。以下代码将重现该问题:

In [1]: import pandas as pd
        import numpy as np

In [2]: df = pd.DataFrame({'c1' : list('AAABBBCCC'),
                           'c2' : list('abcdefghi'),
                           'c3' : np.random.randn(9),
                           'c4' : np.arange(9)})
        df
Out[2]:     c1  c2  c3          c4
        0   A   a   0.819618    0
        1   A   b   1.764327    1
        2   A   c   -0.539010   2
        3   B   d   1.430614    3
        4   B   e   -1.711859   4
        5   B   f   1.002522    5
        6   C   g   2.257341    6
        7   C   h   1.338807    7
        8   C   i   -0.458534   8

In [3]: def myfun(s):
            """Function does practically nothing"""
            req = s.values
            return pd.Series({'mean' : np.mean(req),
                              'std'  : np.std(req),
                              'foo'  : 'bar'})

In [4]: res = df.groupby(['c1', 'c2'])['c3'].apply(myfun)
        res.head(10)
Out[4]: c1  c2      
        A   a   foo          bar
                mean    0.819618
                std            0
            b   foo          bar
                mean     1.76433
                std            0
            c   foo          bar
                mean    -0.53901
                std            0
        B   d   foo          bar

当然,我希望这样:

Out[4]:         foo  mean      std
        c1  c2     
        A   a   bar  0.819618  0
            b   bar  1.76433   0
            c   bar  -0.53901  0
        B   d   bar  1.43061   0 

当应用到 Series 或 DataFrame 的函数返回时,Pandas 会自动将 Series 转换为 DataFrame。为什么应用于组的函数的行为不同?

我正在寻找能够产生所需输出的答案。解释 pandas.Series.apply 之间行为差异的奖励积分或 pandas.DataFrame.applypandas.core.groupby.GroupBy.apply

最佳答案

一个简单的解决方法是unstack

df = pd.DataFrame({'c1' : list('AAABBBCCC'),
                   'c2' : list('abcdefghi'),
                   'c3' : np.random.randn(9),
                   'c4' : np.arange(9)})

def myfun(s):
    """Function does practically nothing"""
    req = s.values
    return pd.Series({'mean' : np.mean(req),
                      'std'  : np.std(req),
                      'foo'  : 'bar'})

res = df.groupby(['c1', 'c2'])['c3'].apply(myfun)
res.unstack()

enter image description here

关于python-3.x - pandas groupby apply 不会广播到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994804/

相关文章:

6位毫秒的python datetime

python - Kivy 禁用屏幕超时

python - 如何根据特定条件替换列中的某些值?

python - 如何使用循环根据条件对 Pandas 数据框中的列进行子集化?

python - 如何选择数据框的一部分并将其转换为 pandas 中的数组?

python - 使用 matplotlib 基于类别的多色条

Python打印函数

python - Pandas:在数据帧的最后一行添加一个具有单个值的新列

python - 从pandas系列中提取日期时间obj值(单行)

Python:pandas,解析数学运算