9

If I have two numpy 1D arrays, for example

x=np.array([1,2,3])
y=np.array([11,22,33])

How can I zip these into Numpy 2D coordinates arrays? If I do:

x1,x2,x3=zip(*(x,y))

The results are of type list, not Numpy arrays. So I have do

x1=np.asarray(x1)

and so on.. Is there a simpler method, where I do not need to call np.asarray on each coordinate? Is there a Numpy zip function that returns Numpy arrays?

1
  • 2
    np.array([(a,b) for a, b in zip(*(x, y))]) Commented Oct 4, 2014 at 13:49

3 Answers 3

16

Just use

x1, x2, x3 = np.vstack([x,y]).T
Sign up to request clarification or add additional context in comments.

2 Comments

I found np.stack to be more versatile. It is the solution for stacking n-dimensional input arrays.
You can now also simply use np.column_stack((x,y)) or np.stack((x,y), axis=1). I don't know if the .T transpose in this statement is somehow optimized, so it might add unnecessary computation. Either way, my suggestion is to use these helper functions and it makes for cleaner code too.
3

Stack the input arrays depth-wise using numpy.dstack() and get rid of the singleton dimension using numpy.squeeze() and then assign the result to co-ordinate variables x1, x2, and x3 as in:

In [84]: x1, x2, x3 = np.squeeze(np.dstack((x,y)))

# outputs
In [85]: x1
Out[85]: array([ 1, 11])

In [86]: x2
Out[86]: array([ 2, 22])

In [87]: x3
Out[87]: array([ 3, 33])

Comments

0

Using numpy.c_:

x1, x2, x3 = np.c_[x, y]

Output:

# x1
array([ 1, 11])

# x2
array([ 2, 22])

# x3
array([ 3, 33])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.