2

I'm trying to interleave arrays as 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 it, but I was looking to improve this line, data = np.array([x, y[0], x, y[1], x, y[2]]). Is there another 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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mocs
  • 101
  • 10
  • In what way are you threading lists? What do you mean with *threading* here? Please provide clear sample input and sample output and explain what the relation is between the input and output. – Willem Van Onsem Jan 28 '18 at 15:25
  • I am a newbie still learning, but I do have a data set where I have multiple y-data set (like y above) with shared single x-axis. To plot all together, I'd like to create [x,y1,x,y2,x,y3....] in an elegant way (shorter code?) I'm not sure I do explain well for your response. I really appreciate your help. – mocs Jan 28 '18 at 15:28

2 Answers2

4

You can try to use 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 indexes in y that you would like to insert into before insertion.

One can use obj=range(y.shape[0]) for arbitrary length of y.

Please see the tutorial for more information.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tai
  • 7,684
  • 3
  • 29
  • 49
0

Adapted from the answer https://stackoverflow.com/a/5347492/7505395 to Interweaving two numpy arrays:

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)

Output:

[[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]]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69