Stack Arrays Horizontally – NumPy

NumPy – Stack arrays horizontally

To stack two or more arrays horizontally in NumPy, we can use numpy.hstack() function. Pass the arrays in a tuple as argument to hstack() function.

For example, we want to stack arrays a, b, and c horizontally using hstack() function, use the following expression.

numpy.hstack((a, b, c))

Examples

1. Stack two arrays horizontally

In the following program, we take two numpy arrays and stack them horizontally.

Python Program

import numpy as np

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

output = np.hstack((arr1, arr2))

print('array 1\n', arr1)
print('array 2\n', arr2)
print('stacking horizontally...\n', output)
Run Code Copy

Output

array 1
 [[1 2]
 [3 4]]
array 2
 [[5 6]
 [7 8]]
stacking horizontally...
 [[1 2 5 6]
 [3 4 7 8]]

2. Stack three arrays horizontally

In the following program, we take two numpy arrays and stack them horizontally.

Python Program

import numpy as np

arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
arr3 = np.array([[9, 10],[11, 12]])

output = np.hstack((arr1, arr2, arr3))

print('array 1\n', arr1)
print('array 2\n', arr2)
print('array 3\n', arr3)
print('stacking horizontally...\n', output)
Run Code Copy

Output

array 1
 [[1 2]
 [3 4]]
array 2
 [[5 6]
 [7 8]]
array 3
 [[ 9 10]
 [11 12]]
stacking horizontally...
 [[ 1  2  5  6  9 10]
 [ 3  4  7  8 11 12]]

Summary

In this NumPy Tutorial, you learned how to access elements of a numpy array using indexing operator.

Related Tutorials

Code copied to clipboard successfully 👍