【问题标题】:restore index after groupby.size() in pandas在 pandas 中的 groupby.size() 之后恢复索引
【发布时间】:2018-05-15 14:24:12
【问题描述】:

我需要在groupby.size() 之后恢复索引,或者让它可用但有点不适用于.size()。我已经阅读了 Pandas - Restore Index after Groupby 的 stackoverflow 帖子,但所有帮助回复都严格使用 max() 聚合函数,其他人呢?

一些代码示例:

df
Out[39]:
      product_id
order_id    
2103    7546
2103    8278
2103    6790
2104    7546
2104    8278
2104    6790


df.groupby('product_id', as_index=True).size()
Out[67]:
product_id
3587      1
3590      1
3680      2
6735      5
6744      1
6759      6

df.groupby('product_id', as_index=False).size()
Out[68]:
product_id
3587      1
3590      1
3680      2
6735      5
6744      1
6759      6

正如您在将 as_index 参数更改为 TrueFalse 后看到的那样,索引没有任何反应。但一切都适用于.max() aggr 函数。所以,无论如何,问题是如何在groupby.size() 之后恢复索引。

预期输出:

    product_id
index   
2103 3587      1
2104 3590      1
2188 3680      2
2188 6735      5
2188 6744      1
2188 6759      6

【问题讨论】:

  • 你的意思是恢复这里?
  • as_index 将返回的分组对象标签作为索引处理,而不是它们在 df 中的相应索引。你能显示预期的输出吗?
  • 您只想添加一个具有product_id 计数的列吗?在这种情况下,您可以使用 df['count'] = df.product_id.map(df.product_id.value_counts())
  • @Wen 我的意思是在 df 中有索引“order_id”被视为 groupby 之后数据帧中的索引
  • 对于product_id 6790,有两个不同的order_id。应该显示哪一个?

标签: python pandas pandas-groupby


【解决方案1】:

一旦您执行groupby,原始索引就会丢失。这是因为在内部,pandas 使用分组列作为索引。

您可以做的是将索引提升到一列,通过预先计算的系列映射product_id 的计数,然后再次设置索引。

value_counts 可以用于此任务,而不是 groupby.size

df = pd.DataFrame({'product_id': [7546, 8278, 6790, 7546, 8278, 6790]},
                  index=[2103, 2103, 2103, 2104, 2104, 2104])

c = df.product_id.value_counts()

res = df.reset_index()
res['count'] = res['product_id'].map(c)
res = res.set_index('index')

print(res)

       product_id  count
index                   
2103         7546      2
2103         8278      2
2103         6790      2
2104         7546      2
2104         8278      2
2104         6790      2

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 2013-08-14
    • 2017-10-19
    • 2019-12-16
    • 2021-06-24
    • 2020-11-22
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多