How does the pandas Series idxmin() method work?

PandasServer Side ProgrammingProgramming

To get the label name of the minimum value of a pandas series object we can use a function called idxmin(). And this idxmin() is a function of the pandas series constructor, which is used to get the index label of the smallest value from the series elements.

The output of the idxmin() method is an index label. And it will return the Value Error if the given series object doesn’t have any values (empty series). Also, it will neglect the missing values for identifying the smallest number from the elements of the given series object.

If the minimum value is located in multiple positions over the elements of a series object, then it returns the label name of the first occurrence value as an output.

Example 1

Let’s create a pandas series object using a list of 8 integer values, and then apply the idxmin() function to get the row name of the minimum value of the series object.

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

# create a pandas series
s = pd.Series([23, 32, 11, 95, 40, 50, 81, 35])
print(s)

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

Output

The output is given below −

0    23
1    32
2    11
3    95
4    40
5    50
6    81
7    35
dtype: int64

Output of idxmin: 2

The idxmin() method of pandas series object is returned an integer value “2” for the following example, and that integer value represents the row name of the smallest number of the given series object.

Example 2

We have created a pandas series object using a list of integers with date_range index labels. After that, we applied the idxmin() method over the data of the series object “s” to get the index label of the minimum value of the series “s”.

import pandas as pd

# creating range sequence of dates
dates = pd.date_range('2021-01-01', periods=8, freq='m')

#creating pandas Series with date index
s = pd.Series([70, 42, 38, 16, 69, 17, 88, 74], index= dates)
print (s)

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

Output

The output is as follows −

2021-01-31    70
2021-02-28    42
2021-03-31    38
2021-04-30    16
2021-05-31    69
2021-06-30    17
2021-07-31    88
2021-08-31    74
Freq: M, dtype: int64

Output of idxmin: 2021-04-30 00:00:00

The output of the idxmin() method for this example is “2021-04-30 00:00:00”, which means the value at index label “2021-04-30” has the minimum value over the elements of the given series object.

raja
Updated on 08-Mar-2022 09:09:39

Advertisements