python-3.x - 汇总 pandas 数据框中多行的数据
问题描述
我有一个采用这种形式的数据框:
import pandas as pd
dict = {'id':["1001", "1001", "1001", "1002", "1002", "1002", "1003", "1003", "1003"],
'food': ["apple", "ham", "egg", "apple", "pear", "cherry", "cheese", "milk", "cereal"],
'fruit':[1, 0, 0, 1, 1, 1, 0, 0, 0],
'score':[1, 3, 1, 1, 1, 1, 2, 2, 3]}
df = pd.DataFrame(dict)
id food fruit score
0 1001 apple 1 1
1 1001 ham 0 0
2 1001 egg 0 0
3 1002 apple 1 1
4 1002 pear 1 2
5 1002 cherry 1 3
6 1003 cheese 0 0
7 1003 cherry 1 3
8 1003 cheese 0 0
我想创建一个新的数据框,其中有一行用于单个参与者(即相同的 ID),然后是用于自定义数据摘要的列,例如:
- 独特食物的数量
- 总果数
- 总成绩
- 等等
示例输出:
id unique fruits score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
我可以创建一个新的空数据框,然后迭代旧数据框中的唯一 ID,使用逻辑索引来填充列。但是我的数据框有大约 50x10^6 行和大约 200,000 个唯一 ID,所以这需要很长时间。我读过迭代数据框的行效率低下,但我不知道如何将替代解决方案应用于我的数据集。
谢谢。
解决方案
怎么样groupby().agg()
:
df.groupby('id', as_index=False).agg({'food':'nunique',
'fruit':'sum',
'score':'sum'})
输出:
id food fruit score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
推荐阅读
- excel - Use Range.subTotal without listing all indexes of an Array
- javascript - nativescript-vue 项目中的全局 css
- java - 使用意图时从微调器中选择的数据dis并从存储android中选择pdf
- python - Python数组,如何在没有循环的情况下选择一定距离后的一组列和行
- date - Odoo Qweb 报告制造订单 - 承诺日期和网址
- makefile - 如何将目录添加到存储在“$^”变量中的所有文件名
- python - Numba 降低了简单 for 循环函数的性能
- javascript - 将数据保存到 .json
- shiny - 为什么会出现“没有名为 [packagename] 的包”来发布闪亮的应用程序?
- python - 谷歌云 NL:ImportError