Home > OS >  How to save the interleaved values of an array?
How to save the interleaved values of an array?

Time:07-21

I don't know how to put it in words, but I can with an example. I have the following variable

anglesp = np.linspace(0, 2*np.pi,50)

but I want to extract to a new variable the values at the position 0,2,4,...,50 and so on. Something like this:

angles = anglesp[0,2,4,6...]

CodePudding user response:

numpy arrays can take an iterable (of integers) as an index instead of a single position index. In this case, the [] operation will return a new array containing the items at the specified positions within the iterable.

As an example:

>>> A = np.array([0,10,20,30,40])
>>> idx = [0, 2, 4]
>>> A[idx]
np.array([0, 20, 40])

So, in your case, you simply need:

angles = anglesp[range(0,50 1,2)]

CodePudding user response:

You can use np.take() which is faster than “fancy” indexing (indexing arrays using arrays);

import  as np
a = [10, 30, 8, 5, 1, 2]
indices = [0, 1, 4] #make this range(0,51,2) for your example
np.take(a, indices) 

it can be easier to use if you need elements along a given axis for a multiple dimension array. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...] ref:https://numpy.org/doc/stable/reference/generated/numpy.take.html

Example

    import numpy as np
    a=np.array([[ 3290  5847]
 [ 7682  6957]
 [22660  5482]
 [22661 10965]
 [    7  1477]
 [ 7681     3]
 [17541 15717]
 [ 9139  1475]
 [14251  4400]
 [ 7680  9140]
 [ 4758 22289]
 [ 7679  8407]
 [20101 15718]
 [15716  8405]
 [15710 20829]
 [22662    19]])
 print("-------")
 print(np.take(a,(2,4),axis=0))

Output:

[[22660  5482]
 [    7  1477]]
  • Related