在pandas中的groupby.size()之后恢复索引

问题描述 投票:0回答:1

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

一些代码示例:

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
python pandas pandas-groupby
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.