Reputation: 151
I created a view (x1
) to a slice of a NumPy array.
x = np.arange(12).reshape((3,4))
x1 = x[0,:]
If I apply +=
operator, for example, it modifies the data of the original array x
(x1
is the same view to x
)
x1 += 10
However, if I apply something more complicated:
x1 = x1**2 + 10
A new array is assigned to x1
and x1
is no longer a view to x
, which is not what I want.
I am wondering if there's a Pythonic way to enforce to x1
remain as a view?
Upvotes: 1
Views: 57
Reputation: 1463
In these cases, you should use the arr[:]
syntax.
In this way, you refer to the x1 value. It can be considered as a pointer (kind of).
x1[:] = x1**2 + 10
x1
> array([10, 11, 14, 19])
x
> array([[10, 11, 14, 19],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Upvotes: 3