kinder chen
kinder chen

Reputation: 1461

How to write in or replace new values in a conditional array?

I construct an array,

a=np.tile(np.arange(5),4)

a
>>>array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4])

and I set up some condition,

mask=a!=0
a[mask]
>>>array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])

now I wanna replace the odd index elements by the even ones, and I try

a[mask][1::2]=a[mask][::2]
a
array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4])

but it doesn't make any change.

Upvotes: 0

Views: 54

Answers (1)

akuiper
akuiper

Reputation: 214957

Boolean index returns a copy of the data instead of view. As with index arrays, what is returned is a copy of the data, not a view as one gets with slices. Since a[mask] is a copy a[mask][1::2] won't change the original array.

Instead of using a boolean mask, you can keep the original non zero index using np.flatnonzero, subset the index with odd and even positions and then do the assignment with the index:

a=np.tile(np.arange(5),4)
idx = np.flatnonzero(a != 0)
a[idx[1::2]] = a[idx[::2]]
a
# array([0, 1, 1, 3, 3, 0, 1, 1, 3, 3, 0, 1, 1, 3, 3, 0, 1, 1, 3, 3])

Upvotes: 1

Related Questions