查找列的最大值并使用Pandas返回相应的行值

ric*_*hie 88 python pandas

数据结构;

使用Python Pandas我试图找到具有最大值的'Country'和'Place'.

这将返回最大值:

data.groupby(['Country','Place'])['Value'].max()
Run Code Online (Sandbox Code Playgroud)

但是如何获得相应的"国家"和"地方"名称?

unu*_*tbu 134

假设df有一个唯一索引,这将为行提供最大值:

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

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

因此,如果df没有唯一索引,则必须在继续执行上述操作之前使索引唯一.根据DataFrame,有时您可以使用stackset_index使索引唯一.或者,您可以简单地重置索引(因此行重新编号,从0开始):

df = df.reset_index()
Run Code Online (Sandbox Code Playgroud)


小智 36

df[df['Value']==df['Value'].max()]
Run Code Online (Sandbox Code Playgroud)

这将返回具有最大值的整个行

  • 值得注意的是,如果有多个相同的最大值,则返回*所有*行。 (4认同)

HYR*_*YRY 8

国家和地方是系列的索引,如果您不需要索引,可以设置as_index=False:

df.groupby(['country','place'], as_index=False)['value'].max()
Run Code Online (Sandbox Code Playgroud)

编辑:

您似乎希望每个国家/地区都拥有最大价值的地方,以下代码可以执行您想要的操作:

df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))
Run Code Online (Sandbox Code Playgroud)


Erf*_*fan 7

使用DataFrame.nlargest

专用方法是在后台nlargest使用它,这是一种高性能的方法:algorithm.SelectNFramesort_values().head(n)

   x  y  a  b
0  1  2  a  x
1  2  4  b  x
2  3  6  c  y
3  4  1  a  z
4  5  2  b  z
5  6  3  c  z
Run Code Online (Sandbox Code Playgroud)
df.nlargest(1, 'y')

   x  y  a  b
2  3  6  c  y
Run Code Online (Sandbox Code Playgroud)


wai*_*kuo 6

使用的index属性DataFrame.请注意,我没有在示例中键入所有行.

In [14]: df = data.groupby(['Country','Place'])['Value'].max()

In [15]: df.index
Out[15]: 
MultiIndex
[Spain  Manchester, UK     London    , US     Mchigan   ,        NewYork   ]

In [16]: df.index[0]
Out[16]: ('Spain', 'Manchester')

In [17]: df.index[1]
Out[17]: ('UK', 'London')
Run Code Online (Sandbox Code Playgroud)

您还可以通过该索引获取值:

In [21]: for index in df.index:
    print index, df[index]
   ....:      
('Spain', 'Manchester') 512
('UK', 'London') 778
('US', 'Mchigan') 854
('US', 'NewYork') 562
Run Code Online (Sandbox Code Playgroud)

编辑

很抱歉误解了你想要的东西,请尝试以下方法:

In [52]: s=data.max()

In [53]: print '%s, %s, %s' % (s['Country'], s['Place'], s['Value'])
US, NewYork, 854
Run Code Online (Sandbox Code Playgroud)


Arp*_*rma 5

导入熊猫模块

定义您的DataFrame对象,例如df,然后读取文件。

为了以最大值打印“国家和地区”,请使用以下代码行。

    print(df[['Country', 'Place']][df.Value == df.Value.max()])
Run Code Online (Sandbox Code Playgroud)


小智 5

我认为返回具有最大值的行的最简单方法是获取其索引。argmax()可用于返回具有最大值的行的索引。

index = df.Value.argmax()
Run Code Online (Sandbox Code Playgroud)

现在,可以使用索引来获取该特定行的功能:

df.iloc[df.Value.argmax(), 0:2]
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用:

print(df[df['Value']==df['Value'].max()])
Run Code Online (Sandbox Code Playgroud)