In this tutorial, we will look at how to use the numpy hstack method to horizontally stack (or concat) numpy arrays with the help of some examples.
How to concatenate numpy arrays horizontally?
You can use the numpy hstack() function to stack numpy arrays horizontally. It concatenates the arrays in sequence horizontally (column-wise). The following is the syntax.
import numpy as np # tup is a tuple of arrays to be concatenated, e.g. (ar1, ar2, ..) ar_h = np.hstack(tup)
It takes the sequence of arrays to be concatenated as a parameter and returns a numpy array resulting from stacking the given arrays. This function is similar to the numpy vstack() function which is also used to concatenate arrays but it stacks them vertically.
Let’s look at some examples of how to use the numpy hstack() function.
1. Horizontally stack two 1D arrays
Let’s stack two one-dimensional arrays together horizontally.
import numpy as np # create two 1d arrays ar1 = np.array([1, 2, 3]) ar2 = np.array([4, 5, 6]) # hstack the arrays ar_h = np.hstack((ar1, ar2)) # display the concatenated array print(ar_h)
Output:
[1 2 3 4 5 6]
Here, we created two 1D arrays of length 3 and then horizontally stacked them with the hstack() function. The resulting array is also one-dimensional since we are concatenating them horizontally.
You can also stack more than two arrays at once with the numpy hstack() function. Just pass the arrays to be stacked as a tuple. For example, let’s stack three 1D arrays horizontally at once.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
# create two 1d arrays ar1 = np.array([1, 2, 3]) ar2 = np.array([4, 5, 6]) ar3 = np.array([7, 8, 9]) # hstack the arrays ar_h = np.hstack((ar1, ar2, ar3)) # display the concatenated array print(ar_h)
Output:
[1 2 3 4 5 6 7 8 9]
Here we concatenated three arrays of length 3 horizontally. The resulting array is one-dimensional and has length 9. Similarly, you can stack multiple arrays, just pass them in the order you want as a sequence.
2. Horizontally stack a 1D and a 2D array
Now let’s try to stack a 1D array with a 2D array horizontally.
# create a 1d array ar1 = np.array([1, 2]) # create a 2d array ar2 = np.array([[0, 0, 0], [1, 1, 1]]) # hstack the arrays ar_h = np.hstack((ar1, ar2)) # display the concatenated array print(ar_h)
Output:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-6-5f5f4f1cdb7b> in <module> 6 7 # hstack the arrays ----> 8 ar_h = np.hstack((ar1, ar2)) 9 # display the concatenated array 10 print(ar_h) <__array_function__ internals> in hstack(*args, **kwargs) ~\anaconda3\envs\dsp\lib\site-packages\numpy\core\shape_base.py in hstack(tup) 341 # As a special case, dimension 0 of 1-dimensional arrays is "horizontal" 342 if arrs and arrs[0].ndim == 1: --> 343 return _nx.concatenate(arrs, 0) 344 else: 345 return _nx.concatenate(arrs, 1) <__array_function__ internals> in concatenate(*args, **kwargs) ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)
We get an error. This is because the dimensions of the arrays are such that you cannot stack them together horizontally.
If you want to stack the two arrays horizontally, they need to have the same number of rows.
# create an array of shape (2, 1) ar1 = np.array([[1], [2]]) # create a 2d array ar2 = np.array([[0, 0, 0], [1, 1, 1]]) # hstack the arrays ar_h = np.hstack((ar1, ar2)) # display the concatenated array print(ar_h)
Output:
[[1 0 0 0] [2 1 1 1]]
3. Horizontally stack two 2D arrays
You can also horizontally stack two 2D arrays together in a similar way.
# create a 2d array ar1 = np.array([[1, 2], [3, 4], [5, 6]]) # create a 2d array ar2 = np.array([[0, 0], [1, 1], [2, 2]]) # hstack the arrays ar_h = np.hstack((ar1, ar2)) # display the concatenated array print(ar_h)
Output:
[[1 2 0 0] [3 4 1 1] [5 6 2 2]]
Here we stacked two 2d arrays of shape (3, 2) horizontally resulting in an array of shape (3, 4).
For more on the numpy hstack() function, refer to its documentation.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Tutorials on numpy arrays –
- How to sort a Numpy Array?
- Create Pandas DataFrame from a Numpy Array
- Different ways to Create NumPy Arrays
- Convert Numpy array to a List – With Examples
- Append Values to a Numpy Array
- Find Index of Element in Numpy Array
- Read CSV file as NumPy Array
- Filter a Numpy Array – With Examples
- Python – Randomly select value from a list
- Numpy – Sum of Values in Array
- Numpy – Elementwise sum of two arrays
- Numpy – Elementwise multiplication of two arrays
- Using the numpy linspace() method
- Using numpy vstack() to vertically stack arrays
- Numpy logspace() – Usage and Examples
- Using the numpy arange() method
- Using numpy hstack() to horizontally stack arrays
- Trim zeros from a numpy array in Python
- Get unique values and counts in a numpy array
- Horizontally split numpy array with hsplit()