Custom slicing in numpy arrays (is it possible to get specific elements and then every nth)?
I need a more personalized way of fetching data from a numpy array, which I think might seem like generic indexing. Specifically, I want to get some arbitrary, predefined elements, then every nth, starting from a given point.
Let's say for example I want the second (as in index number 2) and fourth element of the array, and then every third element starting from the sixth. So far I am doing:
newArray = np.concatenate(myArray[(2, 4)], myArray[6::3])
Is there a more convenient way to achieve this?
source to share
It is actually identical to what you are doing, but you may find it more convenient:
new_array = my_array[np.r_[2, 4, 6:len(my_array):3]]
np.r_
is basically a concatenation + arange
-like slice.
For example:
In [1]: import numpy as np
In [2]: np.r_[np.arange(5), np.arange(1, 4)]
Out[2]: array([0, 1, 2, 3, 4, 1, 2, 3])
In [3]: np.r_[1, 2, :5]
Out[3]: array([1, 2, 0, 1, 2, 3, 4])
In [4]: np.r_[:5]
Out[4]: array([0, 1, 2, 3, 4])
The downside to this approach is that you are creating a (potentially very large) additional index array. You will end up making the copy anyway, but if it is my_array
very large, your original approach is more efficient.
np.r_
is a bit unreadable (intended for interactive use), but it can be a very convenient way to create arbitrary indexing arrays.
source to share