Coding Ref

How to use numpy.hstack() in Python

How to use numpy.hstack() in Python

In Python, numpy.hstack() is a function that is used to stack arrays in a sequence horizontally (i.e., column-wise).

This means that it concatenates arrays along the second axis, which is the columns in a two-dimensional array.

Syntax

The syntax for numpy.hstack() is as follows:

numpy.hstack(tup)

where tup is a tuple containing the arrays that you want to stack.

Examples

Here are some examples of how to use numpy.hstack() in Python:

Example 1: Stack two arrays horizontally

If you have two arrays, a and b, you can stack them horizontally using the following code:

main.py

import numpy as np

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

c = np.hstack((a, b))

In this case, c will be the resulting array after stacking a and b horizontally.

It will have the following values:

output
array([1, 2, 3, 4, 5, 6])

Example 2: Stack three arrays horizontally

Here is another example where we stack three arrays horizontally:

main.py
import numpy as np

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

d = np.hstack((a, b, c))

In this case, d will be the resulting array after stacking a, b, and c horizontally. It will have the following values:

output
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Conclusion

numpy.hstack() is a very useful function for stacking arrays horizontally in Python. It is especially useful when working with large datasets and can help make your code more efficient and easier to read.

You'll also like

Related tutorials curated for you

    How to use numpy.zeros() in Python

    How to use numpy.percentile() in Python

    NumPy: np.arrange()

    How to use numpy.clip() in Python

    How to use numpy.exp() in Python

    NumPy numpy.transpose()

    ModuleNotFoundError: No module named 'numpy' in Python

    How to use numpy.random.uniform() in Python

    How to use numpy.vstack() in Python

    How to use numpy.round() in Python

    How to use numpy.linspace() in Python

    How to use numpy.ndarray.flatten() in Python