Skip to content

NumPy argmin(): Get Index of the Min Value in Arrays

NumPy argmin Get Index of the Min Value in Arrays Cover Image

In this tutorial, you’ll learn how to master the NumPy argmin() function to find the index position of the minimum value in a NumPy array. The np.argmin() function provides incredible functionality for working with one-dimensional and multi-dimensional arrays. You’ll also learn how to extend the functionality to Pandas DataFrames, allowing you to find values across different columns.

Are you looking to find the index of the maximum value in a NumPy array? You can use the NumPy argmax function for that!

By the end of this tutorial, you’ll have learned:

  • How to use the np.argmin() function to find the index of the lowest value in a NumPy array
  • How to work with one-dimensional and multi-dimensional arrays to find the index of the minimum values, including working with different axes
  • How to extend the np.argmin() function to Pandas DataFrames

Understanding the NumPy argmin Function

In this section, you’ll learn how the np.argmin() function works and what different parameters are available within the function. This can be important first step in understanding how to use the function. Let’s take a look at what makes up the function:

# Understanding the NumPy argmin() Function
import numpy as np
np.argmin(a, axis=None, out=None, keepdims=<no value>)

We can see that the function accepts four parameters, only one of which is required. The table below breaks down the different parameters and their default arguments:

ParameterDescriptionDefault ValueAccepted Values
a=The input arrayN/Aarray-like
axis=Which axis to search for the min value along. If None, flattens the array.Noneinteger
out=If provided, the result will be inserted into this array.Nonearray
keepdims=If set to True, the axes which are reduced are left in the result as dimensions with size one.<no value>boolean
The parameters and default arguments of the NumPy argmin() function

Now that you have a strong understanding of the design of the NumPy argmin() function, let’s start diving into a number of examples.

How to Use the NumPy argmin Function with a One-Dimensional Array

In it’s most straightforward form, the NumPy argmin function can search across a one-dimensional array. In this case, the function will return the index position of the minimum value in the array. Let’s see what this looks like:

# Using NumPy argmin() With a One-Dimensional Array
import numpy as np

arr = np.array([10, 7, 4, 11, 12, 6])
print(np.argmin(arr))

# Returns: 2

Let’s break down what the code above is doing:

  1. We import numpy using the alias np
  2. We create an array, arr, which contains six unique values
  3. We then print the result of passing our array into the np.argmin() function

The function returns 2. This represents the index position of the minimum value in the array. Because NumPy arrays are zero-based indexed, 2 represents the third item in the list.

We can then access the corresponding value of this index item by indexing the array, as shown below:

# Accessing the Minimum Value in a NumPy Array Using argmin()
import numpy as np

arr = np.array([10, 7, 4, 11, 12, 6])
min_idx = np.argmin(arr)
print(arr[min_idx])

# Returns: 4

In the following section, you’ll learn how to use the np.argmin() function with two-dimensional arrays.

How to Use NumPy argmin Function with Two-Dimensional Arrays

The NumPy argmin function can also be used with two-dimensional arrays. When using two or more dimensions, the function provides different functionality for returning indices of minimum values.

Let’s see what happens when we pass a two-dimensional array into the np.argmin() function:

# Using np.argmin() with Multi-Dimensional Arrays with Default Arguments
import numpy as np

arr = np.array([
    [3, 7, 1, 2],
    [9, 3, 5, 1],
    [0, 1, 6, 4]
])

print(np.argmin(arr))

# Returns: 8

In the code block above, we loaded a two-dimensional array into the np.argmin() function. The function returned a single index position. This result may surprise you! So let’s explore why this is happening.

By default, the np.argmin() function will use axis=None as its default argument. Since no axis is specified, NumPy will return the index of a flattened version of the array. This means that, by default, NumPy will convert the array into a single dimension and find the index of the minimum value.

In the following two sections, you’ll learn how to customize the behavior of this to get the indices of minimum values row-wise and column-wise.

Finding the Index of the Minimum Value Row-Wise with NumPy argmin

We can use the np.argmin() function’s axis= parameter to customize how NumPy searches for minimum values. By using axis=1, we instruct NumPy to search for the minimum value in each “row” of the array. Let’s see what this looks like:

# Finding the Index of the Minimum Value Row-Wise with np.argmin()
import numpy as np

arr = np.array([
    [3, 7, 1, 2],
    [9, 3, 5, 1],
    [0, 1, 6, 4]
])

print(np.argmin(arr, axis=1))

# Returns: [2 3 0]

In the code block above, we return an array of three different values. This corresponds with the number of “rows” in the array.

The image below illustrates what this process looks like:

Understanding how the np.argmin() Function Works
Understanding how the np.argmin() Function Works

In the following section, you’ll learn how the NumPy argmin function can search for minimum values column-wise.

Finding the Index of the Minimum Value Column-Wise with NumPy argmin

By modifying the axis= parameter to pass in 0, we can find the indices of the minimum values searching column-wise. This allows us to find the minimum values across the 0th axis. Let’s see what this looks like:

# Finding the Index of the Minimum Value Column-Wise with np.argmin()
import numpy as np

arr = np.array([
    [3, 7, 1, 2],
    [9, 3, 5, 1],
    [0, 1, 6, 4]
])

print(np.argmin(arr, axis=0))

# Returns: [2 2 0 1]

We can see that the function returns an array of four values. This corresponds with the number of values in each of the inner arrays.

In the following section, you’ll learn how to use the argmin function with Pandas.

Using NumPy argmin with Pandas

In this section, you’ll learn how to find the row in a Pandas DataFrame with the minimum value in a given column. You’ll also learn how to return the value of a given column based on finding the minimum value in another column.

Because the np.argmin() function can accept an array-like value as input, we can pass in numeric columns from a Pandas DataFrame Series. Let’s load a sample DataFrame and find the index of the minimum value:

# Using np.argmin() with a Pandas DataFrame
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Name': ['Nik', 'Kate', 'Evan', 'Kyra'],
    'Score': [70, 85, 82, 67],
    'Location': ['Toronto', 'New York', 'Atlanta', 'Seattle']})

print(np.argmin(df['Score']))

# Returns: 3

We can see that by passing in a Pandas column as a Series, that the function returns the index of the row corresponding with the minimum value.

We can access the row’s information by using the .iloc accessor. Let’s see what this looks like:

# Accessing the Row with the Minimum Value in Another Column
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Name': ['Nik', 'Kate', 'Evan', 'Kyra'],
    'Score': [70, 85, 82, 67],
    'Location': ['Toronto', 'New York', 'Atlanta', 'Seattle']})

min_idx = np.argmin(df['Score'])
print(df.iloc[min_idx])

# Returns: 
# Name           Kyra
# Score            67
# Location    Seattle
# Name: 3, dtype: object

Finally, we can also access the value of a column based on the minimum value being found in another Pandas column. Similarly, this can be done using the .iloc accessor, as shown below:

# Accessing a Value with the Minimum Value in Another Column
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Name': ['Nik', 'Kate', 'Evan', 'Kyra'],
    'Score': [70, 85, 82, 67],
    'Location': ['Toronto', 'New York', 'Atlanta', 'Seattle']})

min_idx = np.argmin(df['Score'])
print(df.iloc[min_idx, 0])

# Returns: Kyra

In the code block above, we use the .iloc accessor to access the value in the 0th column to access the name of the user that had the minimum score.

Frequently Asked Questions

How does NumPy argmin handle multiple minimum values?

When multiple minimum values are found in a NumPy array, only the index of the first minimum value is returned.

How does NumPy argmin handle missing values?

By default, NumPy will treat missing values as the minimum value. To ignore missing values, you can use the np.nanargmin() function to ignore missing values.

Conclusion

In this tutorial, you learned how to use the powerful np.argmin() function. The function allows you to find the index position of the minimum value in an array. You first learned how the function works by understanding its parameters and default arguments. Then, you learned how to use the function with one-dimensional and multi-dimensional arrays. Finally, you learned how to use the function with Pandas DataFrames.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

Your email address will not be published. Required fields are marked *