我有一个数据框,在列上有一个3级深度多索引.我想计算行(sum(axis=1)
)中的小计,其中我在其中一个级别上求和,同时保留其他级别.我想我知道如何使用level
关键字参数来做到这一点pd.DataFrame.sum
.但是,我很难想到如何将这笔钱的结果合并到原始表中.
建立:
import numpy as np import pandas as pd from itertools import product np.random.seed(0) colors = ['red', 'green'] shapes = ['square', 'circle'] obsnum = range(5) rows = list(product(colors, shapes, obsnum)) idx = pd.MultiIndex.from_tuples(rows) idx.names = ['color', 'shape', 'obsnum'] df = pd.DataFrame({'attr1': np.random.randn(len(rows)), 'attr2': 100 * np.random.randn(len(rows))}, index=idx) df.columns.names = ['attribute'] df = df.unstack(['color', 'shape'])
给出一个漂亮的框架:
说我想降低shape
水平.我可以跑:
tots = df.sum(axis=1, level=['attribute', 'color'])
得到我的总数是这样的:
有了这个,我想把它放到原来的框架上.我想我可以用一种有点麻烦的方式做到这一点:
tots = df.sum(axis=1, level=['attribute', 'color']) newcols = pd.MultiIndex.from_tuples(list((i[0], i[1], 'sum(shape)') for i in tots.columns)) tots.columns = newcols bigframe = pd.concat([df, tots], axis=1).sort_index(axis=1)
有更自然的方法吗?