How does the pandas Series idxmax() method work?

The idxmax() method of the pandas series constructor is used to get the index label of maximum value over the series data.

As we know, the pandas series is a single-dimensional data structure object with axis labels. And we can access the label of a maximum value of the series object by applying the idxmax() method to that series object.

The output of the idxmax method is an index value, which refers to the label name or row indices where the largest value exists. The data type of the idxmax() method has the same type of series index labels.

If the maximum value is available in multiple locations, then the idxmax method will return the first-row label name as an output. The method will return Value Error if the given series object doesn’t have any values (empty series).

Example 1

Let’s create a pandas series object with 10 random integer values between 10 to 100 range and apply the idxmax() function to get the label name of the max value over the series elements.

# import pandas package
import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series(np.random.randint(10,100, 10))
print("Series object:")

# Apply idxmax function
print('Output of idxmax:')


The output is as follows −

Series object:
0    40
1    80
2    86
3    29
4    60
5    69
6    55
7    96
8    91
9    74
dtype: int32

Output of idxmax:

The output of the idxmax() method for the following example is “7” and it indicates the row name/label name of the maximum value of the given series element.

Example 2

In the following example, we have created a pandas Series object “series” using a python dictionary, and the series having named index labels with integer values. After that, we applied the idxmax() method to get the label name of the maximum number.

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'Black':78, 'White':52,'Red':94, 'Blue':59,'Green':79})

# Apply idxmax function
print('Output of idxmax:',series.idxmax())


The output is given below −

Black    78
White    52
Red      94
Blue     59
Green    79
dtype: int64

Output of idxmax: Red

As we can see in the above output block, The output of the idxmax() method is “Red”. And it is the name of that particular row that is the maximum number over the series elements.