I’m trying to change non-adjacent values of an array simultaneously, and it doesn’t seem to be working. Trying the example below, the code does not break, but the values do not change. I have run into the same problem using recarrays. Has anyone run into this before? Any thoughts? For example:
import numpy as np
simulants = np.zeros([10, 5])
simulants[:, 4] =np.array([5,25, 10, 5, 45, 30, 60, 1, 80, 80])
simulants[simulants[:,4]==5][:,0]=np.array([1, 2])
The order of indexing can matter. Try:
The reason why order matters is because
simulants[:,0]is a view, whilesimulants[simulants[:,4]==5]is a (sub)copy of the array. (Modifying a view of an array modifies the underlying array. Modifying a copy does not.)simulants[:,0]is a view because it uses basic slicing.simulants[simulants[:,4]==5]is a copy because it uses a bool ndarray which triggers advanced indexing.Edit: As @eryksun points out in the comments, the assignment could be better handled with a single index: