簡體   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