Python groupby.value_counts() 之后的熊猫 reset_index

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39778686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:41:39  来源:igfitidea点击:

pandas reset_index after groupby.value_counts()

pythonpandasdataframedata-manipulationdata-science

提问by muon

I am trying to groupby a column and compute value counts on another column.

我正在尝试对一列进行分组并计算另一列上的值计数。

import pandas as pd
dftest = pd.DataFrame({'A':[1,1,1,1,1,1,1,1,1,2,2,2,2,2], 
               'Amt':[20,20,20,30,30,30,30,40, 40,10, 10, 40,40,40]})

print(dftest)

dftest looks like

dftest 看起来像

    A  Amt
0   1   20
1   1   20
2   1   20
3   1   30
4   1   30
5   1   30
6   1   30
7   1   40
8   1   40
9   2   10
10  2   10
11  2   40
12  2   40
13  2   40

perform grouping

进行分组

grouper = dftest.groupby('A')
df_grouped = grouper['Amt'].value_counts()

which gives

这使

   A  Amt
1  30     4
   20     3
   40     2
2  40     3
   10     2
Name: Amt, dtype: int64

what I want is to keep top two rows of each group

我想要的是保留每组的前两行

Also, I was perplexed by an error when I tried to reset_index

此外,当我尝试执行时,我对错误感到困惑 reset_index

df_grouped.reset_index()

which gives following error

这给出了以下错误

df_grouped.reset_index() ValueError: cannot insert Amt, already exists

df_grouped.reset_index() ValueError: 无法插入 Amt,已经存在

回答by jezrael

You need parameter namein reset_index, because Seriesname is same as name of one of levels of MultiIndex:

您需要参数namein reset_index,因为Series名称与以下级别之一的名称相同MultiIndex

df_grouped.reset_index(name='count')

Another solution is renameSeriesname:

另一个解决方案是名称:renameSeries

print (df_grouped.rename('count').reset_index())

   A  Amt  count
0  1   30      4
1  1   20      3
2  1   40      2
3  2   40      3
4  2   10      2


More common solution instead value_countsis aggregate size:

更常见的解决方案value_counts是聚合size

df_grouped1 =  dftest.groupby(['A','Amt']).size().reset_index(name='count')

print (df_grouped1)
   A  Amt  count
0  1   20      3
1  1   30      4
2  1   40      2
3  2   10      2
4  2   40      3