[英]How to find average and maximum in an hour of dataframe pandas?
[英]How to find rows with maximum in a group in a pandas dataframe
我有一個 pandas dataframe 像這樣:
指數 | dmc1 | 標准桿 | 假 | 發生 |
---|---|---|---|---|
0 | d1 | p1 | 一個 | 1 |
1 | d1 | p2 | b | 1 |
2 | d1 | p3 | c | 1 |
3 | d1 | p3 | d | 2 |
4 | d2 | p1 | e | 1 |
5 | d2 | p2 | F | 1 |
6 | d2 | p2 | G | 2 |
7 | d2 | p3 | H | 1 |
df = pd.DataFrame({'dmc1': ['d1', 'd1', 'd1', 'd1','d2', 'd2', 'd2', 'd2'],
'par': ['p1', 'p2', 'p3', 'p3', 'p1', 'p2', 'p2', 'p3'],
'dummy': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
'occur': ['1', '1', '1', '2', '1', '1', '2', '1']})
我想按“dmc1”和“par”對這個表進行分組,並在每個組中找到“occur”值最高的成員並只保留這些行。 所以我希望得到這樣的結果:
指數 | dmc1 | 標准桿 | 假 | 發生 |
---|---|---|---|---|
0 | d1 | p1 | 一個 | 1 |
0 | d1 | p2 | b | 1 |
0 | d1 | p3 | d | 2 |
0 | d2 | p1 | e | 1 |
0 | d2 | p2 | G | 2 |
0 | d2 | p3 | H | 1 |
我正在使用 python 3.6.10
我多次找到這個解決方案:
idx = df.groupby(['dmc1','par'])['occur'].idxmax()
df_short = data.loc[idx]
但在我的情況下,它會引發錯誤: AttributeError: 'SeriesGroupBy' object has no attribute 'idmax'
我還發現了使用“idxmax()”而不是“idmax()”的提示,但這也會引發錯誤:raise ValueError
很高興有一個在 python 3.6 中運行的解決方案。
您需要先將值轉換為數字:
df['occur'] = df['occur'].astype(int)
df_short = data.loc[df.groupby(['dmc1','par'])['occur'].idxmax()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.