在groupby.value_counts()之后的 pandas reset_index [英] pandas reset_index after groupby.value_counts()

查看:797
本文介绍了在groupby.value_counts()之后的 pandas reset_index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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看起来像

dftest looks like

    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

进行分组

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

给出

   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

此外,当我尝试reset_index

df_grouped.reset_index()

出现以下错误

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

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

推荐答案

您需要在name .reset_index.html"rel =" nofollow noreferrer> reset_index ,因为Series名称与MultiIndex级别之一的名称相同:

You need parameter name in reset_index, because Series name is same as name of one of levels of MultiIndex:

df_grouped.reset_index(name='count')

另一种解决方案是 rename Series名称:

Another solution is rename Series name:

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


相反,更常见的解决方案value_counts


More common solution instead value_counts is aggregate 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

这篇关于在groupby.value_counts()之后的 pandas reset_index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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