尝试使用groupby查找每月5个最大值 [英] Attempting to find the 5 largest values per month using groupby
本文介绍了尝试使用groupby查找每月5个最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试显示每个月的nc_type
的前三个值.我尝试使用n_largest
,但是按日期并没有这样做.
I am attempting to show the top three values of nc_type
for each month. I tried using n_largest
but that doesn't do it by date.
原始数据:
area nc_type occurred_date
0 Filling x 12/23/2015 0:00
1 Filling f 12/22/2015 0:00
2 Filling s 9/11/2015 0:00
3 Filling f 2/17/2016 0:00
4 Filling s 5/3/2016 0:00
5 Filling g 8/29/2016 0:00
6 Filling f 9/9/2016 0:00
7 Filling a 6/1/2016 0:00
转换为:
df.groupby([df.occurred_date.dt.month, "nc_type"])["rand"].count()
转换后的数据:
occurred_date nc_type
1 x 3
y 4
z 13
w 24
f 34
..
12 d 18
g 10
w 44
a 27
g 42
推荐答案
场景1
MultiIndex系列
occurred_date nc_type
1.0 x 3
y 4
z 13
w 24
f 34
12.0 d 18
g 10
w 44
a 27
g 42
Name: test, dtype: int64
致电sort_values
+ groupby
+ head
:
df.sort_values(ascending=False).groupby(level=0).head(2)
occurred_date nc_type
12.0 w 44
g 42
1.0 f 34
w 24
Name: test, dtype: int64
根据情况将head(2)
更改为head(5)
.
Or, expanding upon my comment with nlargest
, you could do:
df.groupby(level=0).nlargest(2).reset_index(level=0, drop=1)
occurred_date nc_type
1.0 f 34
w 24
12.0 w 44
g 42
Name: test, dtype: int64
场景2
3-col数据框
Scenario 2
3-col dataframe
occurred_date nc_type value
0 1.0 x 3
1 1.0 y 4
2 1.0 z 13
3 1.0 w 24
4 1.0 f 34
5 12.0 d 18
6 12.0 g 10
7 12.0 w 44
8 12.0 a 27
9 12.0 g 42
您可以使用sort_values
+ groupby
+ head
:
You can use sort_values
+ groupby
+ head
:
df.sort_values(['occurred_date', 'value'],
ascending=[True, False]).groupby('occurred_date').head(2)
occurred_date nc_type value
4 1.0 f 34
3 1.0 w 24
7 12.0 w 44
9 12.0 g 42
根据情况将head(2)
更改为head(5)
.
场景3
MultiIndex Dataframe
test
occurred_date nc_type
1.0 x 3
y 4
z 13
w 24
f 34
12.0 d 18
g 10
w 44
a 27
g 42
或者,使用nlargest
.
df.groupby(level=0).test.nlargest(2)\
.reset_index(level=0, drop=1)
occurred_date nc_type
1.0 f 34
w 24
12.0 w 44
g 42
Name: test, dtype: int64
这篇关于尝试使用groupby查找每月5个最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文