我有一个数据框,用于表示一个文件,通过该文件我将两列分组,返回聚合计数。现在我想按最大计数值排序,但是我得到以下错误:
KeyError:'count'
通过agg count列查看组是某种索引,所以不知道如何做到这一点,我是Python和Panda的初学者。 这是实际的代码,如果您需要更多详细信息,请告诉我们:
def answer_five():
df = census_df#.set_index(['STNAME'])
df = df[df['SUMLEV'] == 50]
df = df[['STNAME','CTYNAME']].groupby(['STNAME']).agg(['count']).sort(['count'])
#df.set_index(['count'])
print(df.index)
# get sorted count max item
return df.head(5)
答案 0 :(得分:33)
我认为您需要添加reset_index
,然后将参数ascending=False
添加到sort_values
,因为sort
会返回:
FutureWarning:sort(columns = ....)已弃用,请使用sort_values(by = .....) .sort_values(['count'],ascending = False)
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'] \
.count() \
.reset_index(name='count') \
.sort_values(['count'], ascending=False) \
.head(5)
样品:
df = pd.DataFrame({'STNAME':list('abscscbcdbcsscae'),
'CTYNAME':[4,5,6,5,6,2,3,4,5,6,4,5,4,3,6,5]})
print (df)
CTYNAME STNAME
0 4 a
1 5 b
2 6 s
3 5 c
4 6 s
5 2 c
6 3 b
7 4 c
8 5 d
9 6 b
10 4 c
11 5 s
12 4 s
13 3 c
14 6 a
15 5 e
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'] \
.count() \
.reset_index(name='count') \
.sort_values(['count'], ascending=False) \
.head(5)
print (df)
STNAME count
2 c 5
5 s 4
1 b 3
0 a 2
3 d 1
但似乎你需要Series.nlargest
:
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'].count().nlargest(5)
或:
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'].size().nlargest(5)
size
和count
之间的差异是:
样品:
df = pd.DataFrame({'STNAME':list('abscscbcdbcsscae'),
'CTYNAME':[4,5,6,5,6,2,3,4,5,6,4,5,4,3,6,5]})
print (df)
CTYNAME STNAME
0 4 a
1 5 b
2 6 s
3 5 c
4 6 s
5 2 c
6 3 b
7 4 c
8 5 d
9 6 b
10 4 c
11 5 s
12 4 s
13 3 c
14 6 a
15 5 e
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME']
.size()
.nlargest(5)
.reset_index(name='top5')
print (df)
STNAME top5
0 c 5
1 s 4
2 b 3
3 a 2
4 d 1
答案 1 :(得分:7)
我不确切知道你的df是怎样的。但是如果你必须按照其数量对几个类别的频率进行排序,那么从df中切割一个系列并对系列进行排序会更容易:
series = df.count().sort_values(ascending=False)
series.head()
请注意,本系列将使用该类别的名称作为索引!
答案 2 :(得分:0)
我同意@Christoph Schranz从数据帧中切出一系列内容
df[['STNAME','CTYNAME']].groupby('STNAME')['CTYNAME'].count().nlargest(3)