【问题标题】:Summarise data over several rows in pandas data frame汇总 pandas 数据框中多行的数据
【发布时间】:2020-02-24 21:19:32
【问题描述】:

我有一个采用这种形式的数据框:

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

谢谢。

【问题讨论】:

  • df.groupby('id').agg({'fruit':'sum','score':'sum','food':'nunique'})
  • 你可以使用 df.groupby('id')

标签: python-3.x pandas loops vectorization summarization


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    由于pandas >= 0.25.0 我们为此使用了named aggregations,因此我们可以在其中进行聚合,同时为我们的列提供一个更具信息性的名称,因为我们进行了聚合:

    所以在本例中,我们可以一次性创建unique 列。

    df.groupby('id').agg(
        unique=('food', 'nunique'),
        fruits=('fruit', 'sum'),
        score=('score', 'sum')
    ).reset_index()
    
         id  unique  fruits  score
    0  1001       3       1      1
    1  1002       3       3      6
    2  1003       2       1      3
    

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 2020-08-22
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      相关资源
      最近更新 更多