Multi-numpy arrays

I am trying to alternate arrays as shown below.

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9])

Desired Result:

[[1,2,3,4,5],[4,6,2,6,9],[1,2,3,4,5],[5,9,8,7,4],[1,2,3,4,5],[3,2,5,4,9]]

Is there an elegant way to do this?


This is the way I wrote, but I wanted to improve this line. data=np.array([x,y[0],x,y[1],x,y[2]])Any other way to write this?

x=np.array([1,2,3,4,5])     
y=np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]]) 

data=np.array([x,y[0],x,y[1],x,y[2]])
print(data)
+2
source share
2 answers

You can try using np.insert

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]])
np.insert(y, obj=(0, 1, 2), values=x, axis=0)

array([[1, 2, 3, 4, 5],
       [4, 6, 2, 6, 9],
       [1, 2, 3, 4, 5],
       [5, 9, 8, 7, 4],
       [1, 2, 3, 4, 5],
       [3, 2, 5, 4, 9]])

(0, 1, 2)refers to the indices in ythat you would like to insert before inserting.

EDIT . For any length yyou can use obj=range(y.shape[0]). Thanks for the suggestion of Chiel.

See more details tutorial.

+3
source

fooobar.com/questions/135357/... numpy:

import numpy as np
x=np.array([1,2,3,4,5])     
y=np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]]) # fixed missing []

x_enh = np.array([x]*len(y)) # blow up x to y size 

c = np.empty((y.size * 2,), dtype=y.dtype).reshape(y.size,5) # create correctly sized empty
c[0::2] = x_enh   # interleave using 2 steps starting on 0
c[1::2] = y       # interleave using 2 steps starting on 1

print(c)

:

[[1 2 3 4 5]
 [4 6 2 6 9]
 [1 2 3 4 5]
 [5 9 8 7 4]
 [1 2 3 4 5]
 [3 2 5 4 9]]
0

Source: https://habr.com/ru/post/1671165/


All Articles