0

Let's say I have this array:

import numpy as np
np.array([[0,2,7],[-3,4,0],[12,10,12]])

I'm trying to change the values of one column if one or more values in the column are less than zero. The code should be general and not just for this array How do I set all of the values in the middle vector to -3?

1 Answer 1

2

You could use a mask to filter the columns where some values are negative. That same mask can then be used to also select the replacement value: in the example below the columns where at least one item is negative, will be replaced by columns where the values are all equal to that minimum value.

>>> a = np.array([[0,2,7],[-3,4,0],[12,10,12], [0, -1, 3]]).T
>>> a
array([[ 0, -3, 12,  0],
       [ 2,  4, 10, -1],
       [ 7,  0, 12,  3]])
>>> mask = np.any(a < 0, axis=0)
>>> a[:,mask] = np.min(a[:,mask], axis=0)
>>> a
array([[ 0, -3, 12, -1],
       [ 2, -3, 10, -1],
       [ 7, -3, 12, -1]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.