问题描述
使用Python熊猫我正在尝试找到Country
& Place
带有最大值.
Using Python Pandas I am trying to find the Country
& Place
with the maximum value.
这将返回最大值:
data.groupby(['Country','Place'])['Value'].max()
但是如何获得相应的Country
和Place
名称?
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,有时您可以使用stack
或set_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返回相应的行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!