Programing

pandas DataFrame에서 column의 값이 최대 인 행 찾기

lottogame 2020. 5. 13. 07:59
반응형

pandas DataFrame에서 column의 값이 최대 인 행 찾기


특정 열의 값이 최대 인 행을 어떻게 찾을 수 있습니까?

df.max() 각 열의 최대 값을 알려 드리겠습니다. 해당 행을 얻는 방법을 모르겠습니다.


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

이 기능은 idxmaxPandas API에서 이름으로 업데이트 되었지만 Pandas 0.16부터는 argmax여전히 존재하며 동일한 기능을 수행합니다 (보다 느리게 실행되는 것처럼 보입니다 idxmax).

또한 바로 사용할 수있는 numpy.argmax등, numpy.argmax(df['A'])-이 둘 중 하나와 같은 것을 제공 pandas으로 빨리 적어도 기능 및 나타납니다 idxmax피상적 관찰에.

이전에는 (주석에서 언급했듯이) 최대 요소의 행 위치 인덱스 내에서 정수 위치argmax 를 제공하는 별도의 함수로 존재 하는 것으로 나타났습니다 . 예를 들어, 행 'a'에서 'e'와 같이 문자열 값을 색인 레이블로 사용하는 경우 최대 값이 행 'd'가 아닌 행 4에서 발생 함을 알고 싶을 수 있습니다. 그러나, 팬더 0.16에 나열된 모든 방법은 위의 경우에만 제공 라벨 으로부터 문제의 행에 대해, 그리고 당신이 내 라벨의 위치 정수를 원한다면 당신은 지금 (까다로운 일이 될 수있는 수동을 얻을 중복 된 것을해야 행 레이블이 허용됩니다).IndexIndex

일반적으로 idxmax세 가지 접근 방식 ( argmax, 여전히 존재하는 idxmaxnumpy.argmax)에 대한 유사 동작으로 의 이동 은 나쁜 일이라고 생각합니다. 최대의 위치 정수 위치를 요구하는 것이 매우 일반적이므로 더 일반적입니다. 특히 중복 행 레이블이 일반적인 응용 프로그램에서 일부 색인 내에서 해당 위치 레이블원하는 것보다

예를 들어, 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

따라서 여기서는 순진한 사용은 idxmax충분하지 않지만 이전 형식은 최대 행 argmax위치를 정확하게 제공합니다 (이 경우 위치 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.

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.


You might also try 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

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:

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

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.


The direct ".argmax()" solution does not work for me.

The previous example provided by @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

returns the following message :

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.

So that my solution is :

df['A'].values.argmax()

mx.iloc[0].idxmax()

This one line of code will give you how to find the maximum value from a row in dataframe, here 'mx' is the dataframe and iloc[0] indicates the 0th index.


The idmax of the DataFrame returns the label index of the row with the maximum value and the behavior of argmax depends on version of pandas (right now it returns a warning). If you want to use the positional index, you can do the following:

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

or import numpy as np max_row = np.argmax(df['A'].values)

Note that if you use np.argmax(df['A']) behaves the same as df['A'].argmax().

참고URL : https://stackoverflow.com/questions/10202570/find-row-where-values-for-column-is-maximal-in-a-pandas-dataframe

반응형