With an ndarray.view, one can do:
import numpy as np
a = np.arange(6)
b = a.view()
b[...] = [5, 5, 5, 5, 5, 5]
a and b are now both [5, 5, 5, 5, 5, 5].
Now, can I do the same with slicing/indexing? So that the view does not show the full array, but just a slice? Something like:
import numpy as np
a = np.arange(6)
idx = [0, 2, 4]
b = a[idx] # please just return a view into `a` here
b[...] = [5, 5, 5]
Now a is of course still [0, 1, 2, 3, 4, 5] but I'd like to have it to be [5, 1, 5, 3, 5, 5].
This would be very useful when mapping between different arrays.
As mentioned in the comments, we can get views when dealing with patterned strides for indexing.
Let's take a look at few cases.
1) Case #1: Starting index = 0 and with a stride of 2:
In [129]: a = np.arange(6) # Input array
In [130]: idx = [0,2,4] # Simulating these indices for indexing
In [131]: b = a[::2] # Get view
In [132]: b[...] = [5, 5, 5] # Assign values
In [133]: a
Out[133]: array([5, 1, 5, 3, 5, 5]) # Verify
2) Case #2: Starting index = 1 and with a stride of 2:
In [134]: a = np.arange(6) # Input array
In [135]: idx = [1,3,5] # Simulating these indices for indexing
In [136]: b = a[1::2] # Get view
In [137]: b[...] = [5, 5, 5] # Assign values
In [138]: a
Out[138]: array([0, 5, 2, 5, 4, 5]) # Verify
This method is extensible to multi-dimensional arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With