熊猫DataFrame——查找列的值最大的行

时间:2021-10-29 04:21:56

How can I find the row for which the value of a specific column is maximal?

如何找到某列的值为最大值的行?

df.max() will give me the maximal value for each column, I don't know how to get the corresponding row.

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

5 个解决方案

#1


137  

You just need the argmax() (now called idxmax) function. It's straightforward:

只需使用argmax()(现在称为idxmax)函数。这是简单的:

>>> 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

This function was updated to the name idxmax in the Pandas API, though as of Pandas 0.16, argmax still exists and performs the same function (though appears to run more slowly than idxmax).

这一功能被更新到熊猫API中idxmax的名称,但在大熊猫0.16的情况下,argmax仍然存在并执行相同的功能(尽管看起来运行速度比idxmax慢)。

You can also just use numpy.argmax, such as numpy.argmax(df['A']) -- it provides the same thing as either of the two pandas functions, and appears at least as fast as idxmax in cursory observations.

你也可以用numpy。argmax(比如numpy.argmax(df['A']))——它提供了与两个熊猫函数中的任何一个都相同的功能,并且在粗略的观察中出现的速度至少与idxmax一样快。

Previously (as noted in the comments) it appeared that argmax would exist as a separate function which provided the integer position within the index of the row location of the maximum element. For example, if you have string values as your index labels, like rows 'a' through 'e', you might want to know that the max occurs in row 4 (not row 'd'). However, in pandas 0.16, all of the listed methods above only provide the label from the Index for the row in question, and if you want the position integer of that label within the Index you have to get it manually (which can be tricky now that duplicate row labels are allowed).

在前面(如注释中所指出的),argmax作为一个单独的函数存在,它提供了最大元素的行位置索引中的整数位置。例如,如果您有字符串值作为索引标签,比如行a到行e,您可能想知道最大值出现在第4行(而不是第d行)。然而,在大熊猫0.16中,所有上面列出的方法只提供标签索引的行,如果你想要这个职位标签内的整数索引你必须手动把它(这可能会非常棘手,现在允许重复的行标签)。

In general, I think the move to idxmax-like behavior for all three of the approaches (argmax, which still exists, idxmax, and numpy.argmax) is a bad thing, since it is very common to require the positional integer location of a maximum, perhaps even more common than desiring the label of that positional location within some index, especially in applications where duplicate row labels are common.

总的来说,我认为此举idxmax-like行为三个方法(argmax,仍然存在,idxmax numpy.argmax)是一件坏事,因为它是非常常见的要求最高的位置整数位置,甚至比欲望更常见的标签位置位置在一些指标,特别是在应用程序中重复的行标签是常见的。

For example, consider this toy DataFrame with a duplicate row label:

例如,考虑这个带有重复行标签的玩具DataFrame:

In [19]: dfrm
Out[19]: 
          A         B         C
a  0.143693  0.653810  0.586007
b  0.623582  0.312903  0.919076
c  0.165438  0.889809  0.000967
d  0.308245  0.787776  0.571195
e  0.870068  0.935626  0.606911
f  0.037602  0.855193  0.728495
g  0.605366  0.338105  0.696460
h  0.000000  0.090814  0.963927
i  0.688343  0.188468  0.352213
i  0.879000  0.105039  0.900260

In [20]: dfrm['A'].idxmax()
Out[20]: 'i'

In [21]: dfrm.ix[dfrm['A'].idxmax()]
Out[21]: 
          A         B         C
i  0.688343  0.188468  0.352213
i  0.879000  0.105039  0.900260

So here a naive use of idxmax is not sufficient, whereas the old form of argmax would correctly provide the positional location of the max row (in this case, position 9).

因此,单纯地使用idxmax是不够的,而旧的argmax格式可以正确地提供max行的位置(在本例中是位置9)。

This is exactly one of those nasty kinds of bug-prone behaviors in dynamically typed languages that makes this sort of thing so unfortunate, and worth beating a dead horse over. If you are writing systems code and your system suddenly gets used on some data sets that are not cleaned properly before being joined, it's very easy to end up with duplicate row labels, especially string labels like a CUSIP or SEDOL identifier for financial assets. You can't easily use the type system to help you out, and you may not be able to enforce uniqueness on the index without running into unexpectedly missing data.

在动态类型化语言中,这正是一种令人讨厌的容易出错的行为,这使得这类事情如此不幸,值得一试。如果您正在编写系统代码,并且您的系统突然在某些数据集上被使用,而这些数据集在连接之前并没有得到正确的清理,那么很容易以重复的行标签结束,尤其是像CUSIP或SEDOL标识符这样的字符串标签。您不能轻松地使用类型系统来帮助您,而且您可能无法在索引上执行唯一性,而不会遇到意外丢失的数据。

So you're left with hoping that your unit tests covered everything (they didn't, or more likely no one wrote any tests) -- otherwise (most likely) you're just left waiting to see if you happen to smack into this error at runtime, in which case you probably have to go drop many hours worth of work from the database you were outputting results to, bang your head against the wall in IPython trying to manually reproduce the problem, finally figuring out that it's because idxmax can only report the label of the max row, and then being disappointed that no standard function automatically gets the positions of the max row for you, writing a buggy implementation yourself, editing the code, and praying you don't run into the problem again.

所以剩下希望你的单元测试覆盖一切(他们没有,或者更可能没有人写过任何测试),否则(很可能)你只是等待,看看你碰巧撞到这个错误在运行时,在这种情况下,你可能要下降很多小时的工作从数据库输出结果,爆炸头靠墙在IPython试图手动复制问题,终于弄清楚,这是因为idxmax只能报告最大的标签行,然后是失望,没有标准函数自动获取最大值的位置为你行,写一个车自己实现,编辑代码,祈祷你不要再遇到这个问题了。

#2


60  

You might also try idxmax:

你也可以试试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

#3


17  

Both above answers would only return one index if there are multiple rows that take the maximum value. If you want all the rows, there does not seem to have a function. But it is not hard to do. Below is an example for Series; the same can be done for DataFrame:

如果有多个行取最大值,以上两个答案只返回一个索引。如果你想要所有的行,似乎没有函数。但这并不难做到。下面是级数的一个例子;对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

#4


2  

df.iloc[df['columnX'].argmax()]

argmax() would provide the index corresponding to the max value for the columnX. iloc can be used to get the row of the DataFrame df for this index.

argmax()将为columnX提供与最大值相对应的索引。可以使用iloc获取该索引的DataFrame df的行。

#5


0  

The argmax and idmax of the DataFrame returns the label index of the row with the maximum value (at least with newer version of pandas). If you want to use the positional index, you can do the following:

DataFrame的argmax和idmax返回具有最大值的行的标签索引(至少对于较新的熊猫版本)。如果您想使用位置索引,可以执行以下操作:

max_row = np.argmax(df['A'].values)
df['A'].values[max_row]

where numpy was imported as np as is standard. Note that if you use np.argmax(df['A']), label indexing is used.

当numpy被导入为np时,它是标准的。注意,如果使用np.argmax(df['A']),则使用标签索引。

#1


137  

You just need the argmax() (now called idxmax) function. It's straightforward:

只需使用argmax()(现在称为idxmax)函数。这是简单的:

>>> 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

This function was updated to the name idxmax in the Pandas API, though as of Pandas 0.16, argmax still exists and performs the same function (though appears to run more slowly than idxmax).

这一功能被更新到熊猫API中idxmax的名称,但在大熊猫0.16的情况下,argmax仍然存在并执行相同的功能(尽管看起来运行速度比idxmax慢)。

You can also just use numpy.argmax, such as numpy.argmax(df['A']) -- it provides the same thing as either of the two pandas functions, and appears at least as fast as idxmax in cursory observations.

你也可以用numpy。argmax(比如numpy.argmax(df['A']))——它提供了与两个熊猫函数中的任何一个都相同的功能,并且在粗略的观察中出现的速度至少与idxmax一样快。

Previously (as noted in the comments) it appeared that argmax would exist as a separate function which provided the integer position within the index of the row location of the maximum element. For example, if you have string values as your index labels, like rows 'a' through 'e', you might want to know that the max occurs in row 4 (not row 'd'). However, in pandas 0.16, all of the listed methods above only provide the label from the Index for the row in question, and if you want the position integer of that label within the Index you have to get it manually (which can be tricky now that duplicate row labels are allowed).

在前面(如注释中所指出的),argmax作为一个单独的函数存在,它提供了最大元素的行位置索引中的整数位置。例如,如果您有字符串值作为索引标签,比如行a到行e,您可能想知道最大值出现在第4行(而不是第d行)。然而,在大熊猫0.16中,所有上面列出的方法只提供标签索引的行,如果你想要这个职位标签内的整数索引你必须手动把它(这可能会非常棘手,现在允许重复的行标签)。

In general, I think the move to idxmax-like behavior for all three of the approaches (argmax, which still exists, idxmax, and numpy.argmax) is a bad thing, since it is very common to require the positional integer location of a maximum, perhaps even more common than desiring the label of that positional location within some index, especially in applications where duplicate row labels are common.

总的来说,我认为此举idxmax-like行为三个方法(argmax,仍然存在,idxmax numpy.argmax)是一件坏事,因为它是非常常见的要求最高的位置整数位置,甚至比欲望更常见的标签位置位置在一些指标,特别是在应用程序中重复的行标签是常见的。

For example, consider this toy DataFrame with a duplicate row label:

例如,考虑这个带有重复行标签的玩具DataFrame:

In [19]: dfrm
Out[19]: 
          A         B         C
a  0.143693  0.653810  0.586007
b  0.623582  0.312903  0.919076
c  0.165438  0.889809  0.000967
d  0.308245  0.787776  0.571195
e  0.870068  0.935626  0.606911
f  0.037602  0.855193  0.728495
g  0.605366  0.338105  0.696460
h  0.000000  0.090814  0.963927
i  0.688343  0.188468  0.352213
i  0.879000  0.105039  0.900260

In [20]: dfrm['A'].idxmax()
Out[20]: 'i'

In [21]: dfrm.ix[dfrm['A'].idxmax()]
Out[21]: 
          A         B         C
i  0.688343  0.188468  0.352213
i  0.879000  0.105039  0.900260

So here a naive use of idxmax is not sufficient, whereas the old form of argmax would correctly provide the positional location of the max row (in this case, position 9).

因此,单纯地使用idxmax是不够的,而旧的argmax格式可以正确地提供max行的位置(在本例中是位置9)。

This is exactly one of those nasty kinds of bug-prone behaviors in dynamically typed languages that makes this sort of thing so unfortunate, and worth beating a dead horse over. If you are writing systems code and your system suddenly gets used on some data sets that are not cleaned properly before being joined, it's very easy to end up with duplicate row labels, especially string labels like a CUSIP or SEDOL identifier for financial assets. You can't easily use the type system to help you out, and you may not be able to enforce uniqueness on the index without running into unexpectedly missing data.

在动态类型化语言中,这正是一种令人讨厌的容易出错的行为,这使得这类事情如此不幸,值得一试。如果您正在编写系统代码,并且您的系统突然在某些数据集上被使用,而这些数据集在连接之前并没有得到正确的清理,那么很容易以重复的行标签结束,尤其是像CUSIP或SEDOL标识符这样的字符串标签。您不能轻松地使用类型系统来帮助您,而且您可能无法在索引上执行唯一性,而不会遇到意外丢失的数据。

So you're left with hoping that your unit tests covered everything (they didn't, or more likely no one wrote any tests) -- otherwise (most likely) you're just left waiting to see if you happen to smack into this error at runtime, in which case you probably have to go drop many hours worth of work from the database you were outputting results to, bang your head against the wall in IPython trying to manually reproduce the problem, finally figuring out that it's because idxmax can only report the label of the max row, and then being disappointed that no standard function automatically gets the positions of the max row for you, writing a buggy implementation yourself, editing the code, and praying you don't run into the problem again.

所以剩下希望你的单元测试覆盖一切(他们没有,或者更可能没有人写过任何测试),否则(很可能)你只是等待,看看你碰巧撞到这个错误在运行时,在这种情况下,你可能要下降很多小时的工作从数据库输出结果,爆炸头靠墙在IPython试图手动复制问题,终于弄清楚,这是因为idxmax只能报告最大的标签行,然后是失望,没有标准函数自动获取最大值的位置为你行,写一个车自己实现,编辑代码,祈祷你不要再遇到这个问题了。

#2


60  

You might also try idxmax:

你也可以试试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

#3


17  

Both above answers would only return one index if there are multiple rows that take the maximum value. If you want all the rows, there does not seem to have a function. But it is not hard to do. Below is an example for Series; the same can be done for DataFrame:

如果有多个行取最大值,以上两个答案只返回一个索引。如果你想要所有的行,似乎没有函数。但这并不难做到。下面是级数的一个例子;对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

#4


2  

df.iloc[df['columnX'].argmax()]

argmax() would provide the index corresponding to the max value for the columnX. iloc can be used to get the row of the DataFrame df for this index.

argmax()将为columnX提供与最大值相对应的索引。可以使用iloc获取该索引的DataFrame df的行。

#5


0  

The argmax and idmax of the DataFrame returns the label index of the row with the maximum value (at least with newer version of pandas). If you want to use the positional index, you can do the following:

DataFrame的argmax和idmax返回具有最大值的行的标签索引(至少对于较新的熊猫版本)。如果您想使用位置索引,可以执行以下操作:

max_row = np.argmax(df['A'].values)
df['A'].values[max_row]

where numpy was imported as np as is standard. Note that if you use np.argmax(df['A']), label indexing is used.

当numpy被导入为np时,它是标准的。注意,如果使用np.argmax(df['A']),则使用标签索引。