Numpy zip function

Question:

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?

Asked By: Håkon Hægland

||

Answers:

Just use

x1, x2, x3 = np.vstack([x,y]).T
Answered By: Daniel

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])
Answered By: kmario23

Using numpy.c_:

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

Output:

# x1
array([ 1, 11])

# x2
array([ 2, 22])

# x3
array([ 3, 33])
Answered By: mozway