Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多索引数据帧的最大值_Python_Pandas_Dataframe_Pandas Groupby_Multi Index - Fatal编程技术网

Python 多索引数据帧的最大值

Python 多索引数据帧的最大值,python,pandas,dataframe,pandas-groupby,multi-index,Python,Pandas,Dataframe,Pandas Groupby,Multi Index,我有一个多索引数据帧,如下所示 +-------+----+------+ | | | %age | +-------+----+------+ | Group | Id | | | 0 | 18 | 75 | | 0 | 30 | 12 | | 0 | 42 | 13 | | 1 | 18 | 12 | | 1 | 30 | 75 | | 1 | 42 | 13 | | 2 | 18 |

我有一个多索引数据帧,如下所示

+-------+----+------+
|       |    | %age |
+-------+----+------+
| Group | Id |      |
| 0     | 18 | 75   |
| 0     | 30 | 12   |
| 0     | 42 | 13   |
| 1     | 18 | 12   |
| 1     | 30 | 75   |
| 1     | 42 | 13   |
| 2     | 18 | 13   |
| 2     | 30 | 12   |
| 2     | 42 | 75   |
+-------+----+------+
我想从每个组中获取最大值,但与其他许多问题不同,我还想显示所有索引级别的列。 像这样:

+-------+----+------+
|       |    | %age |
| Group | Id |      |
| 0     | 18 | 75   |
| 1     | 30 | 75   |
| 2     | 42 | 75   |
+-------+----+------+


我试过这个答案


但我得到的输出显示了整个数据帧,为我提供了更简单的解决方案-
reset\u index
isin
应被省略,并添加
loc
,用于选择by
多索引值:

df = df_pct.loc[df_pct.groupby(level=[0])['%age'].idxmax()]
print (df)
          %age
Group Id      
0     18    75
1     30    75
2     42    75
详细信息

print (df_pct.groupby(level=[0])['%age'].idxmax())
Group
0    (0, 18)
1    (1, 30)
2    (2, 42)
Name: %age, dtype: object
编辑:

对于具有
多索引的top N,可与以下一起使用:


感谢您的及时回复,您能否建议,使用上述解决方案,我如何获得每组的前3个或前5个最大值。提前谢谢。
print (df_pct.groupby(level=[0])['%age'].idxmax())
Group
0    (0, 18)
1    (1, 30)
2    (2, 42)
Name: %age, dtype: object
N = 2
df1 = (df_pct.sort_values(['Group','%age'], ascending=[True, False])
             .groupby(level=[0])['%age']
             .head(N))

print (df1)
Group  Id
0      18    75
       42    13
1      30    75
       42    13
2      42    75
       18    13
Name: %age, dtype: int64