Consider the following operation and slicing applied to two numpy arrays:
In [1]: import numpy as np
In [2]: a = np.array([1,2,3,4])
In [3]: b = np.array([5,6,7,8])
In [4]: a[2:] = 0
In [5]: a = a[::2]
In [6]: b[2:] = 0
In [7]: b = b[::2]
In [8]: a
Out[8]: array([1, 0])
In [9]: b
Out[9]: array([5, 0])
I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like
In [4]: for data in [a,b] :
...: data[2:] = 0
...: data = data[::2]
I understand that it does not work because the effect of data = data[::2]
is to make data
to point a new object, not to change the original objects. So the values of a
and b
are not sliced:
In [5]: a
Out[5]: array([1, 2, 0, 0])
In [6]: b
Out[6]: array([5, 6, 0, 0])
My question is:
How to slice a numpy array referenced by a variable?
In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for
.