python - 我想对 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'])
我感谢您的帮助!
解决方案
我相信您需要按某些级别进行分组-例如,首先通过level=0
withGroupBy.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
推荐阅读
- node.js - 无法将 pdf 文件从机器人发送给 ms 团队中的用户
- android - GearVRf - 使用 GVSphere 图像不可见的场景对象
- javascript - 有没有办法在 CRM/CMS 发送电子邮件之前或之后使用 JavaScript 替换文本?
- sql-server - SQL Server:sp_xml_preparedocument 未从 xml 插入/更新 db 中的数据
- javascript - 如何更改标签中包含的 svg 图像的填充颜色
- regex - 希望 perl 正则表达式替换重新开始并避免 `1 while` 技巧
- python - 循环 Python 脚本
- sql - 将 sql 脚本赋值给变量
- ruby-on-rails - 未知关键字:活动存储 5.2.1.1 中的 content_type
- vb6 - 无法启用文本框,导致运行时错误