Understanding numpy.hstack() function (4 examples)

Updated: February 29, 2024 By: Guest Contributor Post a comment

Introduction

When dealing with arrays in Python, one common task is combining them. This tutorial will focus on the numpy.hstack() function from the well-known NumPy library, which stands for horizontal stack. The numpy.hstack() function is used to stack arrays in sequence horizontally (i.e., column-wise). This is different from vertical stacking, which numpy also supports through another function. By the end of this tutorial, you’ll have a firm understanding of how to use the numpy.hstack() function with multiple practical examples.

Syntax & Parameters of numpy.hstack()

Syntax:

numpy.hstack(tup)

Parameters:

  • tup: sequence of array_like. The arrays must have the same shape along all but the second axis. 1-D arrays are treated as rows.

Returns:

  • stacked: ndarray. The array formed by horizontally stacking the given arrays.

Example 1: Basic Usage

Let’s begin with the most basic use case: stacking two 1D arrays horizontally.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.hstack((a, b))
print(result)

Output:

[1, 2, 3, 4, 5, 6]

This example demonstrates how numpy.hstack() combines two arrays horizontally, resulting in a single array.

Example 2: Stacking More Than Two Arrays

What if you have more than two arrays? numpy.hstack() handles this scenario gracefully.

import numpy as np

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

Output:

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

This shows the flexibility of the numpy.hstack() function in handling multiple array inputs.

Example 3: Stacking 2D Arrays

Moving on to more complex scenarios, let’s examine stacking 2D arrays. When stacking 2D arrays horizontally, numpy.hstack() combines the arrays column by column.

import numpy as np

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

Output:

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

This results in a single 2D array, where the columns of the input arrays are combined.

Example 4: Stacking Arrays of Different Dimensions

A more advanced scenario involves stacking arrays with different dimensions. This can be a bit tricky and requires the arrays to be compatible in terms of shapes for horizontal stacking. To illustrate, let’s try combining a 1D array with a 2D array.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([[4, 5], [6, 7], [8, 9]])
result = np.hstack((a, b)) # This will raise an error

This results in a ValueError since numpy.hstack() requires all input arrays to have the same dimensions across the dimension you are not stacking along. In this case, turning the 1D array into a 2D array by adding an extra dimension allows for horizontal stacking. Here’s how:

a_reshaped = a[:, np.newaxis]
result = np.hstack((a_reshaped, b))
print(result)

Output:

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

In this adjusted approach, the 1D array is reshaped into a 2D array, enabling compatible stacking with the other 2D array.

Conclusion

In conclusion, the numpy.hstack() function is a powerful tool for horizontally combining arrays in Python. Whether you’re working with 1D, 2D, or arrays of different dimensions, understanding how to effectively use this function can significantly enhance your data manipulation capabilities in NumPy. Through these examples, we’ve seen the versatility and utility of numpy.hstack(), from simple array combinations to more complex stacking scenarios.