Numpy zip function

14,769

Solution 1

Just use

x1, x2, x3 = np.vstack([x,y]).T

Solution 2

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])
Share:
14,769
Håkon Hægland
Author by

Håkon Hægland

Researcher at NORCE research, Bergen. Email: [email protected]

Updated on July 24, 2022

Comments

  • Håkon Hægland
    Håkon Hægland almost 2 years

    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?

    • DOOM
      DOOM over 9 years
      np.array([(a,b) for a, b in zip(*(x, y))])
  • steffen
    steffen over 6 years
    I found np.stack to be more versatile. It is the solution for stacking n-dimensional input arrays.
  • Qululu
    Qululu over 3 years
    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.