我如何才能找到某一列的值是最大的行?

df.max()会给我每一列的最大值,我不知道如何得到相应的行。


当前回答

使用query()更紧凑和可读的解决方案是这样的:

import pandas as pd

df = pandas.DataFrame(np.random.randn(5,3),columns=['A','B','C'])
print(df)

# find row with maximum A
df.query('A == A.max()')

它还返回一个DataFrame而不是Series,这对于某些用例来说很方便。

其他回答

非常简单:我们有如下所示的df,我们想在C中打印一行max值:

A  B  C
x  1  4
y  2  10
z  5  9

In:

df.loc[df['C'] == df['C'].max()]   # condition check

Out:

A B C
y 2 10

对我有用的是: df[df['colX'] == df['colX'].max()

然后得到df中colX最大值的行。

然后,如果你只想要索引,你可以在查询的末尾添加.index。

直接的“.argmax()”解决方案不适合我。

前面的例子由@ely提供

>>> import pandas
>>> import numpy as np
>>> df = pandas.DataFrame(np.random.randn(5,3),columns=['A','B','C'])
>>> df
      A         B         C
0  1.232853 -1.979459 -0.573626
1  0.140767  0.394940  1.068890
2  0.742023  1.343977 -0.579745
3  2.125299 -0.649328 -0.211692
4 -0.187253  1.908618 -1.862934
>>> df['A'].argmax()
3
>>> df['B'].argmax()
4
>>> df['C'].argmax()
1

返回以下消息:

FutureWarning: 'argmax' is deprecated, use 'idxmax' instead. The behavior of 'argmax' 
will be corrected to return the positional maximum in the future.
Use 'series.values.argmax' to get the position of the maximum now.

所以我的解是:

df['A'].values.argmax()
mx.iloc[0].idxmax()

这一行代码将告诉你如何从dataframe中的一行中找到最大值,这里mx是dataframe, iloc[0]表示第0个索引。

Use:

data.iloc[data['A'].idxmax()]

data['A'].idxmax() -根据行查找最大值位置 Data.iloc() -返回行