如何在groupby 2列之后保留DataFrame的原始索引? [英] How to keep original index of a DataFrame after groupby 2 columns?

查看:284
本文介绍了如何在groupby 2列之后保留DataFrame的原始索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行 groupby 后,有什么方法可以保留大数据帧的原始索引?我需要这样做的原因是因为我需要将内部合并回我的原始 df(在我的 groupby 之后)以重新获得那些丢失的列.并且索引值是执行合并回的唯一唯一"列.有谁知道我如何实现这一目标?

Is there any way I can retain the original index of my large dataframe after I perform a groupby? The reason I need to this is because I need to do an inner merge back to my original df (after my groupby) to regain those lost columns. And the index value is the only 'unique' column to perform the merge back into. Does anyone know how I can achieve this?

我的 DataFrame 非常大.我的 groupby 看起来像这样:

My DataFrame is quite large. My groupby looks like this:

df.groupby(['col1', 'col2']).agg({'col3': 'count'}).reset_index()

这会从我想要保留的原始数据框中删除我的原始索引.

This drops my original indexes from my original dataframe, which I want to keep.

推荐答案

我认为您正在寻找这种情况下的转换:

I think you are are looking for transform in this situation:

df['count'] = df.groupby(['col1', 'col2'])['col3'].transform('count')

这篇关于如何在groupby 2列之后保留DataFrame的原始索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆