Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ndarray view into slices/indices

Tags:

python

numpy

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.

like image 508
Michael Avatar asked Mar 02 '26 01:03

Michael


1 Answers

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.

like image 113
Divakar Avatar answered Mar 05 '26 00:03

Divakar