使用多索引在pandas中添加小计列

 那永A_334 发布于 2023-02-06 22:47

我有一个数据框,在列上有一个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)

汇总

有更自然的方法吗?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有