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

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


当前回答

如果有多行取最大值,上述两个答案都只返回一个索引。如果你想要所有的行,似乎没有一个函数。 但这并不难做到。下面是一个Series的例子;DataFrame也可以这样做:

In [1]: from pandas import Series, DataFrame

In [2]: s=Series([2,4,4,3],index=['a','b','c','d'])

In [3]: s.idxmax()
Out[3]: 'b'

In [4]: s[s==s.max()]
Out[4]: 
b    4
c    4
dtype: int64

其他回答

你也可以试试idxmax:

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

In [6]: df
Out[6]: 
          A         B         C
0  2.001289  0.482561  1.579985
1 -0.991646 -0.387835  1.320236
2  0.143826 -1.096889  1.486508
3 -0.193056 -0.499020  1.536540
4 -2.083647 -3.074591  0.175772
5 -0.186138 -1.949731  0.287432
6 -0.480790 -1.771560 -0.930234
7  0.227383 -0.278253  2.102004
8 -0.002592  1.434192 -1.624915
9  0.404911 -2.167599 -0.452900

In [7]: df.idxmax()
Out[7]: 
A    0
B    8
C    7

e.g.

In [8]: df.loc[df['A'].idxmax()]
Out[8]: 
A    2.001289
B    0.482561
C    1.579985

如果最大值中有联系,那么idxmax只返回第一个最大值的索引。例如,在下面的DataFrame中:

   A  B  C
0  1  0  1
1  0  0  1
2  0  0  0
3  0  1  1
4  1  0  0

idxmax回报

A    0
B    3
C    0
dtype: int64

现在,如果我们想要所有的索引都对应于max值,那么我们可以使用max + eq来创建一个布尔DataFrame,然后在df上使用它。Index来过滤索引:

out = df.eq(df.max()).apply(lambda x: df.index[x].tolist())

输出:

A       [0, 4]
B          [3]
C    [0, 1, 3]
dtype: object

Use:

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

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

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

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

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

非常简单:我们有如下所示的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