Zip Numpy Arrays

  1. NumPy Zip With the list(zip()) Function
  2. NumPy Zip With the numpy.stack() Function
  3. NumPy Zip With the numpy.column_stack() Function

This tutorial will introduce the methods to zip two 1D NumPy arrays into a single 2D NumPy array in Python.

NumPy Zip With the list(zip()) Function

If we have two 1D arrays and want to zip them together inside a 2D array, we can use the list(zip()) function in Python. This approach involves zipping the arrays together inside a list. The list(zip(a,b)) function takes the arrays a and b as an argument and returns a list. We can then convert the zipped list to an array with the numpy.array() function. See the following code example.

import numpy as np

a = np.array([1,3,5,7])
b = np.array([2,4,6,8])

c = np.array(list(zip(a,b)))

print(c)

Output:

[[1 2]
 [3 4]
 [5 6]
 [7 8]]

We first created the two 1D arrays a and b with the np.array() function and zipped them together with the np.array(list(zip(a,b))) function.

This approach is not very efficient because we have to convert between arrays and lists.

NumPy Zip With the numpy.stack() Function

We can also use the numpy.stack() function to achieve the same goal as the previous example. This approach is more efficient than the previous approach because no type conversion is carried out. The numpy.stack() function is used to join two or more arrays according to a specified axis. We can specify the axis parameter equal to 1 to get a similar result as the previous example. See the following code example.

import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

c = np.stack((a,b), axis = 1)

print(c)

Output:

[[1 2]
 [3 4]
 [5 6]
 [7 8]]

We first created the two 1D arrays a and b with the np.array() function and zipped them together with the np.stack((a,b), axis=1) function.

NumPy Zip With the numpy.column_stack() Function

The numpy.column_stack() function is another method that can be used to zip two 1D arrays into a single 2D array in Python. The numpy.column_stack() function is used to join two or more 1D arrays as columns into a single 2D array. We do not have to specify any axis parameter for this approach. See the following code example.

import numpy as np

a = np.array([1,3,5,7])
b = np.array([2,4,6,8])

d = np.column_stack((a,b))

print(d)

Output:

[[1 2]
 [3 4]
 [5 6]
 [7 8]]

We first created the two 1D arrays a and b with the np.array() function and zipped them together with the np.column_stack(a,b) function.

This approach is the best compared with the previous two methods. Because there is no type-conversion, and we do not have to specify any axis in this approach.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.