【发布时间】:2019-05-12 04:13:24
【问题描述】:
我将数据框按 2 列分组,并按其他列的总和进行汇总。如何通过同一数据框中的第一个分组列获得总计?
例如我的数据框是:
np.random.seed(0)
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
结果:
grouped = df.groupby(by=['A', 'B']).sum()
是:
C D
A B
bar one 0.400157 0.410599
three 2.240893 1.454274
two -0.977278 0.121675
foo one 2.714141 0.340644
three -0.151357 0.333674
two 2.846296 0.905081
我会得到什么:
C D
A B
bar one 0.400157 0.410599
two -0.977278 0.121675
three 2.240893 1.454274
total 1.663773 1.986547
foo one 2.714141 0.340644
two 2.846296 0.905081
three -0.151357 0.333674
total 5.409080 1.579400
怎么做?
更新:我在Pandas groupby and sum total of group 发现了一个类似的问题,这个问题还有 2 个答案。
【问题讨论】:
-
this 能解决你的问题吗?
-
以后为了重现性,请在生成随机值之前添加一个随机种子。
-
@IMCoins - 没有。它添加了一个列,我需要一个新的 multyIndex。
-
@coldspeed - 你说得对,但这只是一个例子。
标签: python pandas dataframe group-by pandas-groupby