【问题标题】:aggregating within multiindex dataframe pandas在多索引数据框 pandas 中进行聚合
【发布时间】:2018-12-01 09:59:29
【问题描述】:

我正在寻求与此多索引数据帧相关的帮助

import numpy as np
import pandas as pd

array = [np.array(['jan','jan','feb','feb','mar','mar']), np.array(['food','rent','food','rent','food','rent'])]

df = pd.DataFrame(np.random.randint(0,high=100,size=(6,1)),index=array,columns=['expense'])

我正在尝试总结整个数据框中“食物”和“租金”的数量 - 最简单的方法是什么?

【问题讨论】:

    标签: python-2.7 pandas dataframe multi-index


    【解决方案1】:

    您可以groupby 索引级别(foodrent 处于级别 1 索引):

    df.groupby(level=1).sum()
    
    #      expense
    #food      166
    #rent      161
    

    【讨论】:

    • df.sum(level=1) ?
    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2023-03-07
    • 2020-10-22
    相关资源
    最近更新 更多