Python | Pandas Series.idxmax ()

idxmax | Python Methods and Functions

Series.idxmax() Pandas Series.idxmax() returns the maximum value string label. If multiple values ​​are equal to the maximum, the label of the first line with that value is returned.

Syntax: Series.idxmax (axis = 0, skipna = True, * args, ** kwargs)

Parameter:
skipna: Exclude NA / null values. If the entire Series is NA, the result will be NA.
axis: For compatibility with DataFrame.idxmax. Redundant for application on Series.

Returns: idxmax: Index of maximum of values.

Example # 1: Use Series.idxmax () to find the index mark that matches the maximum value in a given series object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 10 , 25 , 3 , 25 , 24 , 6 ])

 
# Create index

index_ = [ `Coca Cola` , `Sprite` , ` Coke` , `Fanta` , ` Dew` , `ThumbsUp` ]

 
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

We will now use Series.idxmax () to find the index mark that matches the maximum value in the series.

# return index mark
# maximum value in series

result = sr.idxmax ()

 
# Print result

print (result)

Output:

As we can see in the output, Series.idxmax () returned the index mark of the maximum element in the given series object.

Example # 2: Use Series.idxmax () to find the index mark that matches the maximum value in a given series object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 11 , 21 , 8 , 18 , 65 , 84 , 32 , 10 , 5 , 24 , 32 ])

  
# Create index

index_ = pd.date_range ( ` 2010-10-09` , periods = 11 , freq = `M` )

  
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

Now we will use Series.idxmax () to find the index mark that matches the maximum value in the series.

# return index mark
# maximum value in the series

result = sr.idxmax ()

  
# Print re result

print (result)

Output:

As we can see in the output, Series.idxmax () returned the index mark of the maximum element in this series object.





Python | Pandas Series.idxmax (): StackOverflow Questions

Answer #1

You can use idxmax with axis=1 to find the column with the greatest value on each row:

>>> df.idxmax(axis=1)
0    Communications
1          Business
2    Communications
3    Communications
4          Business
dtype: object

To create the new column "Max", use df["Max"] = df.idxmax(axis=1).

To find the row index at which the maximum value occurs in each column, use df.idxmax() (or equivalently df.idxmax(axis=0)).

Answer #2

Easy solution would be to apply : idxmax() function to get indices of rows with max values. This would filter out all the rows with max value in the group.

In [365]: import pandas as pd

In [366]: df = pd.DataFrame({
"sp" : ["MM1", "MM1", "MM1", "MM2", "MM2", "MM2", "MM4", "MM4","MM4"],
"mt" : ["S1", "S1", "S3", "S3", "S4", "S4", "S2", "S2", "S2"],
"val" : ["a", "n", "cb", "mk", "bg", "dgb", "rd", "cb", "uyi"],
"count" : [3,2,5,8,10,1,2,2,7]
})

In [367]: df                                                                                                       
Out[367]: 
   count  mt   sp  val
0      3  S1  MM1    a
1      2  S1  MM1    n
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
5      1  S4  MM2  dgb
6      2  S2  MM4   rd
7      2  S2  MM4   cb
8      7  S2  MM4  uyi


### Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]                                                       
Out[368]: 
   count  mt   sp  val
0      3  S1  MM1    a
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
8      7  S2  MM4  uyi

### Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values                                                        
Out[369]: array([0, 2, 3, 4, 8])

Answer #3

Use the pandas idxmax function. It"s straightforward:

>>> 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
  • Alternatively you could also use numpy.argmax, such as numpy.argmax(df["A"]) -- it provides the same thing, and appears at least as fast as idxmax in cursory observations.

  • idxmax() returns indices labels, not integers.

    • 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").
    • if you want the integer position of that label within the Index you have to get it manually (which can be tricky now that duplicate row labels are allowed).

HISTORICAL NOTES:

  • idxmax() used to be called argmax() prior to 0.11
  • argmax was deprecated prior to 1.0.0 and removed entirely in 1.0.0
  • back as of Pandas 0.16, argmax used to exist and perform the same function (though appeared to run more slowly than idxmax).
    • argmax function returned the integer position within the index of the row location of the maximum element.
    • pandas moved to using row labels instead of integer indices. Positional integer indices used to be very common, more common than labels, especially in applications where duplicate row labels are common.

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

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.iloc[dfrm["A"].idxmax()]  # .ix instead of .iloc in older versions of pandas
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).

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.

Answer #4

This takes the last. Not the maximum though:

In [10]: df.drop_duplicates(subset="A", keep="last")
Out[10]: 
   A   B
1  1  20
3  2  40
4  3  10

You can do also something like:

In [12]: df.groupby("A", group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]: 
   A   B
A       
1  1  20
2  2  40
3  3  10

Answer #5

Assuming df has a unique index, this gives the row with the maximum value:

In [34]: df.loc[df["Value"].idxmax()]
Out[34]: 
Country        US
Place      Kansas
Value         894
Name: 7

Note that idxmax returns index labels. So if the DataFrame has duplicates in the index, the label may not uniquely identify the row, so df.loc may return more than one row.

Therefore, if df does not have a unique index, you must make the index unique before proceeding as above. Depending on the DataFrame, sometimes you can use stack or set_index to make the index unique. Or, you can simply reset the index (so the rows become renumbered, starting at 0):

df = df.reset_index()

Get Solution for free from DataCamp guru