3

Lets say we have this array and I want to replace the minimum value with number 50

import numpy as np
numbers = np.arange(20)
numbers[numbers.min()] = 50

So the output is [50,1,2,3,....20]

But now I have problems with this:

numbers = np.arange(20).reshape(5,4)
numbers[numbers.min(axis=1)]=50

to get [[50,1,2,3],[50,5,6,7],....]

However I get this error:

IndexError: index 8 is out of bounds for axis 0 with size 5 ....

Any ideas for help?

2
  • numbers.min() returns the minimum value not the index of the array. In your first example, it works because the index and the value of the array are the same. you need to find the index of the minimum number. Commented Nov 19, 2015 at 3:38
  • numbers.min() returns the minimum value in the numpy array, not the index. It works only if you have an array with strictly consecutively increasing values. Better use a function which returns the location of minimum value and then use it to replace with new value. Commented Nov 19, 2015 at 3:41

1 Answer 1

7

You need to use numpy.argmin instead of numpy.min:

In [89]: numbers = np.arange(20).reshape(5,4)

In [90]: numbers[np.arange(len(numbers)), numbers.argmin(axis=1)] = 50
In [91]: numbers
Out[91]: 
array([[50,  1,  2,  3],
       [50,  5,  6,  7],
       [50,  9, 10, 11],
       [50, 13, 14, 15],
       [50, 17, 18, 19]])

In [92]: numbers = np.arange(20).reshape(5,4)

In [93]: numbers[1,3] = -5 # Let's make sure that mins are not on same column

In [94]: numbers[np.arange(len(numbers)), numbers.argmin(axis=1)] = 50

In [95]: numbers
Out[95]: 
array([[50,  1,  2,  3],
       [ 4,  5,  6, 50],
       [50,  9, 10, 11],
       [50, 13, 14, 15],
       [50, 17, 18, 19]])

(I believe my original answer was incorrect, I confused rows and columns, and this is right)

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I didn't think about the argmin() function, thank you that saved my night!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.