繁体   English   中英

在多索引 Pandas 中使用 groupby 添加列

[英]Add column using groupby in multiindex Pandas

我正在尝试根据 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)

改用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM