0

I have a 1D numpy array of values, and a 2D numpy array of values

x = array([4,5,6,7],[8,9,10,11])
y = array([0,1,2,3])

I want to create tuples of each row of y with the row in x

End result being

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

Is there anyway to do this with numpy functions instead of for loops?

Alex Marasco
  • 157
  • 3
  • 10

2 Answers2

2

Let's try:

np.concatenate([list(zip(a,y)) for a in x ])

Output:

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

Or pure python:

list(zip(x.ravel(), np.tile(y,len(x))) )

Output:

[(4, 0), (5, 1), (6, 2), (7, 3), (8, 0), (9, 1), (10, 2), (11, 3)]
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
2

Assuming len(y) divides a size of x, you can merge a flatten view of x with an artificial padding with np.tile and then transpose result:

np.array([x.flatten(), np.tile(y, x.size//len(y))]).T

Note that x.flatten() is a synonym of x.ravel().

mathfux
  • 5,759
  • 1
  • 14
  • 34