【问题标题】:Add column using groupby in multiindex Pandas在多索引 Pandas 中使用 groupby 添加列
【发布时间】:2019-01-26 19:56:52
【问题描述】:

我正在尝试根据 groupby 函数查找列的总和。所以在这个例子中,我想找到所有 bar、baz、foo 和 qux 的总和。

总和将被添加到最后的新列中。我可以得到我需要的结果,但我无法将其加入数据框。

import numpy as np
import pandas as pd


arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

np.random.seed(7) 
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

results=df.groupby(level=[0]).sum(axis=1)

col_names=results.columns.values
hold=[]
for i in col_names:
    hold.append('sum_'+str(i))
results.columns=hold

df=pd.concat([df,results],axis=1)

期望的结果如下。感谢观看

        0          1       2       3    sum_0   sum_1   sum_2   sum_3
bar one  1.69    (0.47)  0.03    0.41    0.90    (0.46)  0.03    (1.35)
bar two  (0.79)  0.00    (0.00)  (1.75)  0.90    (0.46)  0.03    (1.35)
baz one  1.02    0.60    (0.63)  (0.17)  1.52    0.34    (0.87)  (1.62)
baz two  0.51    (0.26)  (0.24)  (1.45)  1.52    0.34    (0.87)  (1.62)
foo one  0.55    0.12    0.27    (1.53)  2.21    0.28    (0.11)  0.50 
foo two  1.65    0.15    (0.39)  2.03    2.21    0.28    (0.11)  0.50 
qux one  (0.05)  (1.45)  (0.41)  (2.29)  1.00    (1.87)  (1.15)  (1.22)
qux two  1.05    (0.42)  (0.74)  1.07    1.00    (1.87)  (1.15)  (1.22)

【问题讨论】:

    标签: python pandas dataframe multi-index


    【解决方案1】:

    改用transform,您可以摆脱该循环的代码。

    df = pd.concat([df, df.groupby(level=0).transform('sum').add_prefix('sum_')], axis=1)
    df
                 0      1      2      3 sum_0  sum_1  sum_2  sum_3
    bar one   1.69  -0.47   0.03   0.41  0.90  -0.46   0.03  -1.35
        two  -0.79   0.00  -0.00  -1.75  0.90  -0.46   0.03  -1.35
    baz one   1.02   0.60  -0.63  -0.17  1.52   0.34  -0.87  -1.62
        two   0.51  -0.26  -0.24  -1.45  1.52   0.34  -0.87  -1.62
    foo one   0.55   0.12   0.27  -1.53  2.21   0.28  -0.11   0.50
        two   1.65   0.15  -0.39   2.03  2.21   0.28  -0.11   0.50
    qux one  -0.05  -1.45  -0.41  -2.29  1.00  -1.87  -1.15  -1.22
        two   1.05  -0.42  -0.74   1.07  1.00  -1.87  -1.15  -1.22
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 2018-04-17
      • 2022-07-19
      • 2016-02-06
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多