Hacen Selahy
Hacen Selahy

Reputation: 79

selecting an element in numpy

a = np.arange(4).reshape(2, 2)
a
[[0, 1]
[2, 3]]
a[  a==[0, 1] ][0] = 1 

Expecting a = [[1, 1], [2, 3]] but 'a' didnt change. what underly this problem. thanks

Upvotes: 2

Views: 55

Answers (2)

yatu
yatu

Reputation: 88236

The problem here is that you're trying to assign to a copy of the array, not a view, hence thendarray remains unchanged.

One way would be to use np.where:

replace_with = np.vstack([np.ones(a.shape[0]), a[:,1]])
np.where((a==[0,1]).all(1)[:,None], replace_with, a)

array([[1., 1.],
       [2., 3.]])

Here replace_with is an ndarray with ones in the first column, and the content of a on the second, since it seems like that is what you're trying to do:

print(replace_with)

array([[1., 1.],
       [1., 3.]])

Upvotes: 2

Hongpei
Hongpei

Reputation: 697

If you look into a==[0, 1] you'll find out that it returns a matrix of

array([[False,  True],
       [False, False]])

already. So what you need is only:

a = np.arange(4).reshape(2, 2)
a[a==[0,1]]=1
a
# array([[1, 1],
#        [2, 3]])

Upvotes: 0

Related Questions