Home > other >  numpy get elements by array of ranges
numpy get elements by array of ranges

Time:11-05

I have a data np.array "A" and np.array with ranges[from-to index] "I" to be obtained from A.

How to create a new np array/or list ?

A=[1 161  51 105 143   2 118 127  37  19   4  29  13 136 129 128 129
 250  52  53  57  53  49  53  57  49  55 177  84  69  85 210   6  43 128
 194 253   0 236 129 131  53  54  56  54  50  48 182 128  52 113  13 169
  57  41 233 128 254 160 128   9  81  75 166  89 178 128 128 128 128 128
 128 177 128  84  81  84 197 206]

I=[[ 0  2]
 [ 2  5]
 [ 5  8]
 [ 8 14]
...
  ]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The new array should be like this:

[[1 161 nul] [51 105 143] ... ] 
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I am not sure why you have a 'null' in one of your intervals. But you can do this using a list comprehension:

import numpy as np
A=np.array([1, 161,  51, 105, 143,   2, 118, 127 , 37,  19,   4 , 29 , 13, 136, 129, 128, 129])

I=[[ 0,  2],
 [ 2  ,5],
 [ 5  ,8],
 [ 8, 14]]

res = [A[i[0]:i[1]] for i in I]

Output:

[array([  1, 161]),
 array([ 51, 105, 143]),
 array([  2, 118, 127]),
 array([ 37,  19,   4,  29,  13, 136])]
  • Related