I have a problem with assigning values to a selected element of an array that I do not understand why it is happening.
I'm programming in pyhton and, although the code is much more complex, the issue I am having can be reproduced with this small code:
Yr = np.arange(0, 10)
Xg = np.arange(0, 10)
Now I want to change the value of an element that I selected as follows:
Yr[Xg>5][2] = 10
... and it does nothing:
In [275]: Yr
Out[275]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Thank you.
I tried changing the type of assigned value, but it does not work either.
CodePudding user response:
It's because it creates a copy of the array So you modify the copy and not the array itself
Yr[Xg>5]
is a new array
Yr = Yr[Xg>5]
Yr[2] = 10
print(Yr) # will print [ 6 7 10 9]
CodePudding user response:
As others mentioned in their answers Yr[Xg>5]
is a new array and any change on it does not apply on the original array, but you can do it by using np.put
like this:
np.put(Yr, np.where(Xg>5)[0][2], 10)
Or simply do this:
Yr[np.where(Xg>15)[0][2]] = 10