I have a simple numpy array, and I want to make a separate array that takes every two elements per two indices
For example:
x = np.arange(0,20)
print(x)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
My goal is to get an array of
[2 3 6 7 10 11 14 15 18 19]
How might I do that? I tried this:
print(x[1:len(x)-1:2])
[ 1 3 5 7 9 11 13 15 17]
but I only get every other index.
You can simply do this using the traditional start:stop:step
convention without any modulo by reshaping your array, indexing, and then flattening it back. Try this -
x.reshape(-1,2)[1::2].flatten()
array([ 2, 3, 6, 7, 10, 11, 14, 15, 18, 19])
This should be significantly faster than approaches where mathematical operations are being used to check each value since this is just reshaping and indexing.
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