Как найти argmin функции

numpy.argmin(a, axis=None, out=None, *, keepdims=<no value>)[source]#

Returns the indices of the minimum values along an axis.

Parameters:
aarray_like

Input array.

axisint, optional

By default, the index is into the flattened array, otherwise
along the specified axis.

outarray, optional

If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.

keepdimsbool, optional

If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.

New in version 1.22.0.

Returns:
index_arrayndarray of ints

Array of indices into the array. It has the same shape as a.shape
with the dimension along axis removed. If keepdims is set to True,
then the size of axis will be 1 with the resulting array having same
shape as a.shape.

Notes

In case of multiple occurrences of the minimum values, the indices
corresponding to the first occurrence are returned.

Examples

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
       [13, 14, 15]])
>>> np.argmin(a)
0
>>> np.argmin(a, axis=0)
array([0, 0, 0])
>>> np.argmin(a, axis=1)
array([0, 0])

Indices of the minimum elements of a N-dimensional array:

>>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
>>> ind
(0, 0)
>>> a[ind]
10
>>> b = np.arange(6) + 10
>>> b[4] = 10
>>> b
array([10, 11, 12, 13, 10, 15])
>>> np.argmin(b)  # Only the first occurrence is returned.
0
>>> x = np.array([[4,2,3], [1,0,3]])
>>> index_array = np.argmin(x, axis=-1)
>>> # Same as np.amin(x, axis=-1, keepdims=True)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
array([[2],
       [0]])
>>> # Same as np.amax(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
array([2, 0])

Setting keepdims to True,

>>> x = np.arange(24).reshape((2, 3, 4))
>>> res = np.argmin(x, axis=1, keepdims=True)
>>> res.shape
(2, 1, 4)

Время на прочтение
2 мин

Количество просмотров 12K

В этой статье я хочу рассказать о нескольких функциях Numpy, которые я использую для анализа данных постоянно. Это ни в коем случае не исчерпывающий список, но думаю, что инструменты, о которых пойдёт речь, пригодятся каждому без исключения.

Сталкиваясь с новой задачей, я раз за разом думал: «Это достаточно специфичная вещь, вряд ли для неё найдётся встроенная функция». В случае с Numpy, чаще я был неправ, чем прав.

Но давайте ближе к делу. Единственная строка импорта, которая нам нужна:


where()

Функция where() возвратит элементы, удовлетворяющие определённому условию. Посмотрим на примере.

Создадим список оценок (произвольных):

Теперь можно воспользоваться where(), чтобы найти оценки большие, скажем, чем 3:

Обратите внимание, что возвращаются индексы искомых элементов.

Но это, разумеется, ещё не всё, функция может принимать два опциональных параметра:

  • первый заменит собой значения, удовлетворяющие условию
  • второй сделает это для значений, условию не удовлетворяющих

Поскольку статья задумана краткой, на этом и остановимся.


argmin(), argmax(), argsort()

Функция argmin() возвращает индекс минимального значения. Для того же массива оценок, что мы использовали выше, результат будет:

argmax(), как вы наверняка догадались, делает прямо противоположное — возвращает индекс максимального элемента:

Последняя из троицы argsort() вернёт список индексов отсортированных элементов массива. Не забывайте про неё: вы столкнётесь с огромным количеством ситуаций, когда это нужно.


intersect1d()

Функция intersect1d() возвратит пересечение двух массивов, т.е. уникальные элементы, которые встречаются в обоих. В отличие от предыдущих примеров, она вернёт не индексы, а сами значения.

Создадим два массива:

Найдём общие элементы:


allclose()

Напоследок рассмотрим функцию allclose(). Она возвратит True, если элементы двух массивов равны в пределах допуска. Опять же, вы не представляете, как часто это нужно при работе с данными.

Объявим два массива, разница между соответствующими элементами которых не более 0.2:

Функция allclose() с допуском в 0.1 должна вернуть False:

Повысим допуск до 0.2, чтобы получить приблизительное равенство массивов:


Напутствие

Не счесть количество раз, когда я был (и есть) виноват в изобретении колеса. Часто мы думаем, что наша проблема уникальна, и никто не догадался создать инструмент для её решения. Иногда это правда, но часто чувствуешь себя последним идиотом, найдя удобную стандартную функцию взамен той, на создание которой уже потратил кучу времени.

Потратьте лучше немного этого времени на изучение возможностей популярных библиотек, ведь именно благодаря им библиотеки и стали популярны.

Спасибо за чтение.

Время чтения 2 мин.

Если вы работаете над проектами по машинному обучению, вам может понадобиться найти максимальное или минимальное значение или индексы в массиве numpy. Вот тут-то и появляется библиотека numpy.

Содержание

  1. Что такое функция np.argmin() в Python?
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Нахождение индекса минимального элемента одномерного массива
  6. Нахождение индексов максимальных элементов многомерного массива

Функция numpy.argmin() используется в Python для получения индексов минимального элемента из массива (одномерный массив) или любой строки или столбца (многомерный массив) любого заданного массива. Функция numpy argmin() принимает arr, axis и out в качестве параметров и возвращает массив.

Синтаксис

numpy.argmin(arr,axis=None,out=None)

Параметры

Функция numpy argmin() принимает три аргумента:

  1. arr: массив, из которого мы хотим получить индексы минимального элемента.
  2. axis: по умолчанию это None. Но для многомерного массива, если мы собираемся найти индекс любого максимума элемента по строкам или по столбцам, мы должны указать axis = 1 или axis = 0 соответственно.
  3. out: если указано, результат будет вставлен в этот массив. Он должен быть соответствующей формы и типа.

Возвращаемое значение

Функция np.argmin() возвращает массив, содержащий индексы минимальных элементов.

Нахождение индекса минимального элемента одномерного массива

См. следующий код.

#Importing numpy

import numpy as np

#We will create an 1D array

arr = np.array([4, 24, 63, 121, 4, 64])

#Printing the array

print(«The array is: «, arr)

#Shape of the array

print(«Shape of the array is : «, np.shape(arr))

#Now we will print index of min value of this array

print(«Index of minimum value of the given array is: «, np.argmin(arr))

Выход

The array is:  [  4  24  63 121   4  64]

Shape of the array is : (6,)

Index of minimum value of the given array is:  0

Объяснение.

В этой программе мы сначала объявили массив с некоторыми случайными числами, заданными пользователем. Затем мы напечатали форму(размер) массива. Затем мы вызвали функцию argmin(), чтобы получить индекс минимального элемента из массива. Мы видим, что минимальный элемент этого массива равен 4, который находится в позиции 0, поэтому выход равен 0.

Нахождение индексов максимальных элементов многомерного массива

См. следующий код.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#Importing numpy

import numpy as np

#We will create a 2D array

#Of shape 4×3

arr = np.array([(1, 9, 4),(6, 55, 4),(1, 3, 40),(5, 6, 4)])

#Printing the array

print(«The array is: «)

print(arr)

print(«Shape of the array is: «, np.shape(arr))

#Now we will find the indices of minimum value for some cases

#Indices of minimum value of each row

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

print(«Indices of minimum value of each row of the array is: «, a)

#Indices of minimum value of each column

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

print(«Indices of minimum value of each column of the array is: «, b)

Выход

The array is:

[[ 1  9  4]

[ 6 55  4]

[ 1  3 40]

[ 5  6  4]]

Shape of the array is: (4, 3)

Indices of minimum value of each row of the array is:  [0 2 0 2]

Indices of minimum value of each column of the array is:  [0 2 0]

Объяснение.

В этой программе мы сначала объявили матрицу размера 4×3; вы также можете увидеть форму матрицы, которая равна(4,3). Затем мы вызвали argmin(), чтобы получить вывод о различных случаях.

This tutorial explains how to use the Numpy argmin function. It explains the syntax of np.argmin, and also shows clear examples.

If you need something specific, you can click on any of the links below. These links will take you to the appropriate section of the tutorial.

Table of Contents:

  • Introduction to Numpy Argmin
  • Syntax
  • Examples

If you really want to understand how Numpy argmin works though, you should probably read the whole tutorial. It will make more sense if you read the whole tutorial.

A quick introduction to Numpy Argmin

Let’s start with a quick introduction to the argmin function.

Numpy argmin function (much like it’s companion function, Numpy argmax) frequently confuses new Numpy users. However, it starts to make sense once you see a clear explanation and clear examples.

In its simplest use, the argmin function returns the index of the minimum value of a Numpy array.

An image that shows argmax retrieving the index of the minimum value of a 1D array.

So it’s similar to the Numpy minimum function, but instead of returning the minimum value, it returns the index of the minimum value.

To make this a little more clear, I’m going to quickly review some basics about Numpy and Python. Knowing these basics should make argmin easier to understand.

Numpy arrays store data

For starters, let’s review what a Numpy arrays are.

Numpy arrays store numeric data in a grid format.

A simple example of a 1D Numpy array with the values [91, 92, 93, 7, 95].

So for example, in the Numpy array above, we have the values 91, 92, 93, 7, and 95, arranged in a one dimensional array.

So Numpy arrays are a special data structure that store numeric data in a grid-like format.

Locations in a Numpy array have an “index”

Next, let’s review Numpy indexes. Indexes are important for the argmin function.

All Numpy arrays have indexes. The values of the index are like numeric addresses for each position in the array.

1-dimensional arrays are simpler to understand than multi-dimensional arrays, so let’s look at a 1D example.

If we have a 1D Numpy array, every location in that array has an index. Again, the index is sort of like a numeric address for each position in the array.

An example of a Numpy array with 5 values, that also shows the associated index value for every item in the array.

If you’re familiar with lists, tuples, and other Python data structures, this probably sounds familiar. Most collections and sequences in Python have indexes, just like these Numpy array indexes.

And just like the indexes for lists and tuples, indexes for Numpy arrays start at 0.

Numpy Argmin Identifies the Minimum Value and Returns the Associated Index

Now, let’s bring this back to the argmin function.

When we call np.argmin(), the argmin function identifies the minimum value in the array.

But instead of retrieving the minimum value itself, argmin retrieves the index that’s associated with the minimum value.

An image that shows argmax retrieving the index of the minimum value of a 1D array.

That’s really all it does! The np.argmin function simply returns the index of the minimum value in the array.

Having said that, there are more complicated ways of using the np.argmin. For example, you can use the function along specific axes. I’ll show you examples of how to do that in the examples section.

But before we look at some examples, let’s look at the syntax.

The syntax of np.argmin

Ok. Let’s take a look at the syntax.

A quick note

One reminder before we look at the syntax

The syntax explanation and the examples below assume that you’ve imported Numpy with the alias ‘np‘.

You can do that with this code:

import numpy as np

Among Python data scientists, this is the common convention for importing Numpy. So, we’ll be using this convention in the following syntax explanation and examples.

With that said, let’s look at the syntax.

np.argmin syntax

The syntax of np.argmin is fairly simple.

You call the function as np.argmin().

An image that explains the syntax of the np.argmin function.

Inside the parenthesis, you have a few parameters that you can use to control how the function works.

Let’s look at those parameters.

The parameters of np.argmin

The np.argmin function really only has 3 parameters:

  • a
  • axis
  • out

The out parameter is somewhat rarely used, so we’re not going to discuss it here.

But let’s look at the a parameter and axis parameter.

a (required)

The a parameter enables you to specify the input array that you want to operate on.

So if you want to operate on an array called myarray, you can call the function as np.argmin(a = myarray).

Keep in mind that you need to provide an argument to this parameter.

Having said that, you don’t need to explicitly use this parameter. Instead, you can pass in an argument by position like this: np.argmin(myarray). The argmin function will assume that the first argument to the function is the input array to be passed to the a= parameter.

Also note that this parameter will accept many data structures as arguments. Typically, we’ll pass in a Numpy array as the argument, but the np.argmin function will also accept “array like” objects, such as Python lists.

axis

The axis parameter enables you to control the axis along which to use argmin.

Remember: Numpy arrays have axes. Axes are like directions along the numpy array.

A visual example of NumPy array axes.

Keep in mind, that the axis parameter is optional. If you use it, np.argmin will retrieve the index values for the minima along particular axes. But if you don’t use it, then argmin will flatten out the array and retrieve the index of the minimum of the flattened array.

To be honest, how axes work is little difficult to understand without examples. So I’ll show you some examples in the examples section bellow. I also strongly recommend that you read our tutorial that explains Numpy axes.

Examples of how to use Numpy Argmin

Ok. Let’s take a look at a few examples.

Things almost always make more sense when you can look at some examples, but that’s particularly true with np.argmin.

Examples:

  • Use argmin on a 1-dimensional array
  • Apply argmin to a 2-dimensional array
  • Use argmin along axis 0
  • Use argmin along axis 1

Run this code first

Before you run any of the examples, you need to import Numpy.

You can do that with the following code:

import numpy as np

When we do this, we’ll be able to call our Numpy functions starting with the alias ‘np‘.

EXAMPLE 1: Use argmin on a 1-dimensional array

Ok, let’s start simple.

Here, we’re going to identify the index of the minimum value of a 1-dimensional Numpy array.

First, let’s just create the array:

my_1d_array = np.array([91,92,93,7,95])

Now, let’s use np.argmin.

np.argmin(a = my_1d_array)

OUT:

3
Explanation

This is a simple example.

This is a 1D array, with several elements. The minimum value of the array is 7.

An image that shows argmax retrieving the index of the minimum value of a 1D array.

The minimum value, 7, is at index position 3, so argmin returns the value ‘3’.

EXAMPLE 2: Apply argmin to a 2-dimensional array

Next, let’s look at how argmin works on a 2-dimensional array.

First, we need to create our array with the Numpy array() function.

my_2d_array = np.array([[8,92,93],[94,9,7]])

Notice that there are some high values and some low values.

Now that we have our 2D array, let’s apply np.argmin.

np.argmin(my_2d_array)

OUT:

5
Explanation

The output for this example is 5. Why?

In this example, we’re operating on a 2-dimensional array.

But, by default, if we’re use np.argmin on a 2-dimensional array and we do not specify an axis, the Numpy argmin function applies a 2-step process.

First, np.argmin flattens the 2-dimensional array to a 1-dimensional array. (Keep in mind, np.argmin will also flatten out higher dimensional arrays).

Second, np.argmin operates on the new flattened array.

An image that shows how Numpy argmin operates on a 2D array by default, by flattening first, then applying argmin.

When we flatten out the array in this example, the minimum value, 7, is at index position 5 of the flattened array.

Therefore, numpy.argmin returns 5.

EXAMPLE 3: Use argmin along axis 0

Next, let’s apply argmin to a 2-dimensional array, and also use the axis parameter.

In this example, we’ll set axis = 0.

We’ll re-use the array that we created in example 2, but if you didn’t run that code already, here’s the code to create our 2D array:

my_2d_array = np.array([[8,92,93],[94,9,7]])

Now that we have our array, let’s use Numpy argmin with axis = 0:

np.argmin(my_2d_array, axis = 0)

OUT:

array([0, 1, 1])
Explanation

This example is harder to understand, so let’s break it down.

Remember what I said earlier: Numpy axes are like directions along a Numpy array. For a 2-dimensional array, the axis-0 direction points downward.

When we use argmin in the axis-0 direction, the function identifies the minimum along that axis and returns the index.

An image showing how argmin operates on a 2-dimensional array when we set axis = 0.

Since this example is a little more complicated, let’s look carefully.

When we set axis = 0, we’re using argmin in the axis-0 direction. Remember, for a 2D array, axis-0 points downward.

Also remember that for a 2D array, every row has an index. So you can see “row 0” and “row 1”. (Again, all Python indexes start at 0, so the “first” row is actually the 0th row.)

From there, argmin simply looks for the minimum value along the axis-0 direction. When it finds the minimum value, argmin returns the row index.

So 0 is the minimum value in the first column, and the row index of that value is 0.

The minimum value in the second column is 9, which is in row 1.

Similarly, the minimum value in the third column is 7, which is also in row 1.

np.argmin outputs the indexes of the minimum values in the axis-0 direction. So the output is [0, 1, 1].

Effectively, when we set axis = 0, it’s like applying argmin along the columns.

EXAMPLE 4: Use argmin along axis 1

Ok. Let’s do one more example.

Let’s apply argmin in the axis-1 direction.

First, let’s create our array (the same array as the previous two examples):

my_2d_array = np.array([[8,92,93],[94,9,7]])

And now, let’s use argmin.

np.argmin(my_2d_array, axis = 1)

OUT:

array([0, 2])
Explanation

This example is also a hard to understand. To understand it, you really need to know how axes work for Numpy arrays.

In this example, we’re applying np.argmin along axis-1. Remember: for 2D Numpy arrays, axis-1 points horizontally.

An image showing how argmin operates on a 2-dimensional array when we set axis = 1.

When we set axis = 1, argmin identifies the minimum value for every row. Then it returns the column index of each minimum value.

So for the first row, the minimum value is 8. That value has a column index of 0.

For the second row, the minimum value is 7. That value has a column index of 2.

So np.argmin outputs the column indexes of the minimum values: [0,2].

If you’re still confused, read more about indexes and axes

I’ve tried to make these examples as clear as possible, but I realize that Numpy argmin is difficult to understand.

Ultimately, to understand Numpy argmin, you need to understand Numpy indexes. You also need to understand how Numpy axes work. Those things being said, if you haven’t already, you should read our tutorial on Numpy axes.

Leave Your Questions in the Comments Section

Do you have other questions about Numpy argmin? Is there something I’ve missed?

If so, just leave your questions in the comments section near the bottom of the page.

Join our course to learn more about Numpy

In this tutorial, I’ve shown you how to use Numpy argmin.

Numpy argmin is useful for some very specific things, but if you’re working with numeric data in Python, there’s a lot more to learn. To use Numpy properly, you’ll need to know many other Numpy functions.

So if you’re serious about learning Numpy, you should consider joining our premium course called Numpy Mastery.

Numpy Mastery will teach you everything you need to know about Numpy, including:

  • How to create Numpy arrays
  • How to Numpy axes work
  • What the “Numpy random seed” function does
  • How to use the Numpy random functions
  • How to reshape, split, and combine your Numpy arrays
  • Applying mathematical operations on Numpy arrays
  • and more …

The course will also show you our unique practice system. This practice system will enable you to memorize all of the Numpy syntax that you learn.

If you’re struggled to remember Numpy syntax, this is the course you’ve been looking for.

If you practice like we show you, you’ll memorize all of the critical Numpy syntax in only a few weeks.

Find out more here:

Learn More About Numpy Mastery

Numpy stands for Numerical Python. With numpy, we can perform mathematical computations at high speed in python. The Numpy library in python consists of a large collection of high-level mathematical functions. These functions are used for handling large, multi-dimensional arrays and matrices in python and for performing various logical and statistical operations on them. Out of the many available functions in numpy, we shall be looking into one such function – Numpy Argmin.

What is numpy argmin?

Numpy argmin is a function in python which returns the index of the minimum element from a given array along the given axis. The function takes an array as the input and outputs the index of the minimum element.

The input array can be a single-dimensional array as well as a multi-dimensional array. We can also perform sorting on the array using this argmin function.

Syntax of Numpy argmin

The syntax of the numpy argmin function is:

numpy.argmin(a, axis=None, out=None)

The function accepts three parameters – a, axis and out.

Parameters of Numpy argmin:

a: It is the array like input given to the function. It is the array for which the index of the minimum element has to be found.

axis: It is an optional parameter which takes an integer value. If not specified, then it is None by default. If specified, then the minimum value’s index is returned along that axis.

out: This is also an optional parameter. If it is provided, then the result of the argmin function will be stored into this array. But, the given array’s size should be compatible with the return array’s shape.

Return Value of Numpy argmin:

index_array: It is an array containing integer values. These integer values contain the index(s) of the minimum value along the given axis.

Numpy argmin() for 1D array

Let us understand with some python code how to use the argmin() function. First, we shall import the numpy library.

Now, we shall take a numpy array and store it into a variable named ‘array’.

array = np.array([10,7,2,1,5,8,11,9])

After creating the array, we shall pass the ‘array’ as an argument to the argmin() function. Then, we shall print the return value of that function.

The output is:

3

The minimum value in the array is 1. Since the indexing starts from 0, the index of 1 – which is 3 – shall be returned by the function.

The Entire Code is:

import numpy as np
array = np.array([10,7,2,1,5,8,11,9])
print(np.argmin(array))

Argmin() for multi dimensional array

We can also use the argmin function to calculate the minimum value for a multi dimensional array. The output will be calculate along the axis of the multi dimensional array.

Let us take a two dimensional array first.

import numpy as np
array = np.array([[10,7,2,1],[5,8,11,9]])

Now, we shall pass the array to the argmin function. We will not be mentioning the ‘axis’ parameter explicitly.

So, axis will have its default value – ‘None’.

Since the ‘axis’ is ‘None’, the output will be the index of the element in the form of a flattened array.

Output:

3

The answer is similar to that obtained in case of the one dimensional array.

The Entire Code is:

import numpy as np
array = np.array([[10,7,2,1],[5,8,11,9]])
print(np.argmin(array))

Numpy Argmin with different axis values

Now, we shall try to change the axis values of the argmin function and see how it changes the output.

Earlier, we were using axis = None. Now we shall first try for axis = 0. We shall take the same two dimensional array as before.

Axis = 0:

import numpy as np
array = np.array([[10,7,2,1],[5,8,11,9]])

Now, in the argmin function, we shall pass ‘axis = 0’ as the second argument.

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

The output will contain an array with the index value of the minimum element for each column of the 2D array.

[1 0 0 0]

In the first column, between 10 and 5, 5 is minimum. So, the index value of 5,which is 1, shall be passed. Similarly the index value for the other elements shall be passed too.

The Entire Code is:

import numpy as np
array = np.array([[10,7,2,1],[5,8,11,9]])
print(np.argmin(array, axis = 0))

Axis = 1:

Now, we shall pass axis = 1 instead of axis = 0.

import numpy as np
array = np.array([[10,7,2,1],[5,8,11,9]])
print(np.argmin(array, axis = 1))

The output will be an array containing indexes of minimum elements along the row of the two dimensional array.

[3 0]

So, in the first row, the minimum element is at position 3 and in the second row, minimum element is at position 0.

Numpy argmin with Condition

We can also apply argmin() function for a given array where the elements fulfill a certain condition. For this, we shall be making use of Masked Arrays in numpy. Masked Arrays are those arrays where the array elements may be invalid entries.

For all the elements which do not fulfill the given condition, we shall mask them and not consider them. Then for the rest of the elements, the index of the minimum value shall be returned.

Here, we shall only include those elements whose value is greater than or equal to 6. So in the MaskedArray, we shall pass the opposite condition, i.e., the elements whose value is less than 6 in order to mask those elements.

import numpy as np
array = np.array([10,7,2,1,5,8,11,9])
array = np.ma.MaskedArray(array, array<6)
print(array)

The printed elements would look something like this:

[10 7 -- -- -- 8 11 9]

Now, we shall print the np.argmin() function’s return value.

Since out of the unmasked elements 7 has the minimum value, its index 1 would be printed.

1

The Entire Code is:

import numpy as np
array = np.array([10,7,2,1,5,8,11,9])
array = np.ma.MaskedArray(array, array<6)
print(array)
print(np.argmin(array))

Numpy Argmin with Matrix

We can also use the argmin function to find an index of minimum elements from a matrix. For that, we will access it using the

Syntax:

numpy.matrix.argmin 

We shall create a matrix using numpy’s matrix function.

import numpy as np
matrix = np.matrix(np.arange(16).reshape((4,4)))
print(matrix)
print(matrix.argmin())

The output is:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

0

Here, 0 is printed as the index of the minimum value 0.

Also, Read

  • NUMPY ARGWHERE WITH EXAMPLES IN PYTHON
  • NumPy argpartition() | Explained with examples

Here are a few questions we hear often when talking about Numpy argmin.

How to handle nan values while using numpy array?

We can mask the nan values present in a given array using the MaskedArray. All the nan values will be masked and not considered for the argmin function.

The code is :

import numpy as np
array = np.array([10, np.nan,2, np.nan,5,8, np.nan,9])
array = np.ma.MaskedArray(array, np.isnan(array))
print(array)
print(np.argmin(array))

The output is:

[10.0 — 2.0 — 5.0 8.0 — 9.0]
2


This sums up everything about Numpy Argmin. If you have any questions, let us know in the comments below.

Until next time, Keep Learning!

Понравилась статья? Поделить с друзьями:
  • Как найти медиану треугольника абс
  • 5 класс биология пасечник как составить кроссворд учебник
  • Как найти длину медианы зная стороны треугольника
  • Как правильно составить претензию на некачественную услугу в сервисном центре образец
  • Как найти партнеров предприятия