查找列的最大值,并使用Pandas返回相应的行值 [英] Find maximum value of a column and return the corresponding row values using Pandas

查看:166
本文介绍了查找列的最大值,并使用Pandas返回相应的行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python熊猫我正在尝试找到Country& Place带有最大值.

Using Python Pandas I am trying to find the Country & Place with the maximum value.

这将返回最大值:

data.groupby(['Country','Place'])['Value'].max()

但是如何获得相应的CountryPlace名称?

But how do I get the corresponding Country and Place name?

推荐答案

假定df具有唯一索引,则该行将具有最大值:

Assuming df has a unique index, this gives the row with the maximum value:

In [34]: df.loc[df['Value'].idxmax()]
Out[34]: 
Country        US
Place      Kansas
Value         894
Name: 7

请注意, idxmax 返回索引标签.因此,如果DataFrame在索引中有重复项,则标签可能不会唯一地标识该行,因此df.loc可能会返回多个行.

Note that idxmax returns index labels. So if the DataFrame has duplicates in the index, the label may not uniquely identify the row, so df.loc may return more than one row.

因此,如果df没有唯一索引,则必须按照上述步骤使索引唯一.取决于DataFrame,有时您可以使用stackset_index来使索引唯一.或者,您可以简单地重置索引(以便重新编号行,从0开始):

Therefore, if df does not have a unique index, you must make the index unique before proceeding as above. Depending on the DataFrame, sometimes you can use stack or set_index to make the index unique. Or, you can simply reset the index (so the rows become renumbered, starting at 0):

df = df.reset_index()

这篇关于查找列的最大值,并使用Pandas返回相应的行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆