首页 > 解决方案 > 我想对 multiindex-dataframe 中一列的行求和,但保留其他列的值

问题描述

我有以下形式的数据框:

                                   Price  Quantity
Date       Mat        Str    Type                 
2016-01-05 2016-02-19 3125.0 C        44     0.069
                             C        44     0.032
                             C        44     0.015
2016-01-06 2016-02-15 3169.0 P        69     0.069

我希望对Quantity列的行求和,但保持 Price 列不变(例如,用平均值制作另一个价格列)

我曾考虑让价格列成为索引的一部分,但由于我的目标是将这个 Df的价格数量与其他类似形状的 Df 进行比较,我可能会遇到一些问题。

这是一些重新创建df的代码:


import pandas as pd



data = [{'Date':'2016-01-05', 'Mat':'2016-02-19', 'Str': 3125.0, 'Type': 'C', 'Quantity':0.069, 'Price':44},
        {'Date':'2016-01-05', 'Mat':'2016-02-19', 'Str': 3125.0, 'Type': 'C', 'Quantity':0.032, 'Price':44},
        {'Date':'2016-01-05', 'Mat':'2016-02-19', 'Str': 3125.0, 'Type': 'C', 'Quantity':0.015, 'Price':44},
        {'Date':'2016-01-06', 'Mat':'2016-02-15', 'Str': 3169.0, 'Type': 'P', 'Quantity':0.069, 'Price':69}]


df1 = pd.DataFrame(data)
df1 = df1.set_index(['Date', 'Mat', 'Str', 'Type'])

我感谢您的帮助!

标签: pythonpandasdataframemulti-index

解决方案


我相信您需要按某些级别进行分组-例如,首先通过level=0withGroupBy.transform来按聚合值填充新列:

df1['Sum'] = df1.groupby(level=0)['Quantity'].transform('sum')
print (df1)
                                   Quantity  Price    Sum
Date       Mat        Str    Type                        
2016-01-05 2016-02-19 3125.0 C        0.069     44  0.116
                             C        0.032     44  0.116
                             C        0.015     44  0.116
2016-01-06 2016-02-15 3169.0 P        0.069     69  0.069

推荐阅读