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?

1
  • Do you expect to have array of tuples here? Commented Oct 13, 2020 at 18:50

2 Answers 2

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().

Sign up to request clarification or add additional context in comments.

2 Comments

Just a side note, flatten() is not a synonym of ravel().
Thanks for a source
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)]

2 Comments

Isn't there a looping inside comprehension you did? Also, np.repeat works in a different manner than OP expects.
@mathfux thanks for pointing out. Updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.