首页 > 解决方案 > 汇总 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,所以这需要很长时间。我读过迭代数据框的行效率低下,但我不知道如何将替代解决方案应用于我的数据集。

谢谢。

标签: python-3.xpandasloopsvectorizationsummarization

解决方案


怎么样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

推荐阅读