10
我想分组列并计算另一列的数值。熊猫reset_index后groupby.value_counts()
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看起来像
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
我要的是让每个小组的前两名行
而且,我被错误困扰,当我试图reset_index
df_grouped.reset_index()
这给下面的错误
df_grouped.reset_index() ValueError: cannot insert Amt, already exists
完美!解决重置索引问题...有没有一种更好的方法来保持排前n行,计数...现在尝试了几件事情后,只有可能的方式,我能想到的是第一个groupby.value_counts,然后子集 – muon
也许需要['nlargest'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html) - ''dftest.groupby(['A','Amt']) .size()。nlargest(3)' – jezrael
不是按组来做的,只给出整体最大的 – muon