How to index multiple array elements at intervals in Python

Suppose I have a list:

import numpy as np a = [2, 4, 6, 8, ..., 1000] # total 500 elements b = np.array(a) # numpy version 

I want to get from the 1st to the 100th, from the 201st to the 300th, from 401 to 500 elements and turn them into a new array.

For this purpose I tried the following codes:

 a_sub = a[0:100] + a[200:300] + a[400:500] b_sub = np.concatenate((b[0:100], b[200:300], b[400:500])) 

But I want to do this with simple oneline indexing

Say:

 a_sub = a[(0:100, 200:300, 400:500)] a_sub = a[[0:100, 200:300, 400:500]] b_sub = b[[0:100, 200:300, 400:500]] b_sub = b[[0:100, 200:300, 400:500]] 

But above all are invalid, and I could not find such an oneliner indexing.

+6
source share
6 answers

You can use reformatting with np.reshape and slicing , as well -

 np.array(a).reshape(-1,100)[::2].ravel() 

If a is a NumPy array, you can do this:

 a.reshape(-1,100)[::2].ravel() 
+3
source

You can convert slices into an array mask (by cutting a single array) and combine the array arrays using the | (or).

 ones = np.ones(b.shape, dtype = bool) mask = ones[ 0:100] | ones[200:300] | ones[400:500] b_sub = b[mask] 

Please note that if your fragments overlap or appear in non-decreasing order, this leads to a different array than your source code (the elements will not be repeated and will always be displayed in the same order as in the original array).

+1
source

well, it's pure python, but maybe it can solve your question

 a = [2, 4, 6, 8, ..., 1000] slices = ((0, 100), (200, 300), (400, 500)) def new_from_slices(list_, slices): return list(itertools.chain(*[list_[s[0]:s[1]] for s in slices])) new_from_slices(a, slices) 
+1
source

You can also use np.split :

 a = range(2, 1002, 2) edges = [100, 200, 300, 400] subarrays = np.split(a, edges) b = np.hstack(subarrays[i] for i in [0, 2, 4]) 
+1
source

two other single line:

 [x for i,x in enumerate(a) if i//100%2==0] #python b[np.arange(len(b))//100%2==0] # numpy 
0
source

or using hstack (+ adds the value element wise)

 a = np.arange(1000) limits = [(0, 100), (200, 300), (400, 500)] b = np.hstack(a[low:high] for low, high in limits) 
0
source

All Articles