How to Get the Position of Max Value of a pandas Series?

PandasServer Side ProgrammingProgramming

In the pandas series constructor, there is a method called argmax() which is used to get the position of maximum value over the series data.

The pandas series is a single-dimensional data structure object with row index values. By using row index values we can access the data.

The argmax() method in the pandas series is used to get the positional index of the maximum value of the series object. The output of the argmax method is an integer value, which refers to the position where the largest value exists.

Example 1

# 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(s)

# Apply argmax function
print('Output of argmax', s.argmax())

Explanation

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

Output

0 81
1 94
2 75
3 13
4 17
5 42
6 45
7 29
8 25
9 59
dtype: int32

Output of argmax: 1

The argmax() method of pandas series object is returned an integer value “1” for the following example, and that integer value represents the position of the maximum value of the given series element.

Example 2

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'Black':10, 'White':29,'Red':82, 'Blue':56,'Green':67})
print(series)

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

Explanation

In the following example, we have created a pandas.Series object “series” using a python dictionary, and the resultant series is having named index labels with integer data. After that, we applied the argmax() method over the data of the series object to get the position of the maximum number.

Output

Black 10
White 29
Red   82
Blue  56
Green 67
dtype: int64

Output of argmax: 2

The output of the argmax() method is 2 for the following example, which means the value at index label “Red” is having a maximum value.

If the maximum value is available in multiple locations, then the argmax method will return the first-row position as output.

raja
Updated on 09-Mar-2022 06:33:40

Advertisements