What is NumPy Hstack in Python?

This recipe explains all you need to know about NumPy Hstack in Python.

When working with arrays in Python, you are likely to come across situations where you need to combine or merge arrays to perform various operations on your data. One essential tool in the NumPy library, a fundamental package for scientific computing with Python, is hstack. Hstack in NumPy stands for "horizontal stack," and it allows a user to concatenate or stack arrays horizontally, effectively adding columns to the given data. In this tutorial, we'll dive into a simple example to understand how to use Python NumPy hstack.

Learn how to build Regression (Linear,Ridge,Lasso) Models in NumPy Python 

How to use Hstack in NumPy Python?

In this tutorial, we will explore a NumPy hstack example to help you learn its application in  to horizontally combine arrays in Python.

Step 1: Import the NumPy Library

Before we delve into using NumPy hstack function, we need to import the necessary library. NumPy is our go-to library for array manipulation and mathematical operations in Python.

import numpy as np

The import numpy as np statement is quite common in Python data science and scientific computing projects. It brings in the NumPy module and assigns it the alias np for brevity.

Step 2: Set up the Input Arrays for Horizontal Stacking

In this step, we create two simple numpy arrays that we will use for demonstration. The first single numpy array a is created with np.ones((3, 3)), resulting in a 3x3 array filled with ones. The second single array b is created by converting a one-dimensional array of 2, 2, 2 into a 3x1 array using reshape.

a = np.ones((3, 3))

b = np.array((2, 2, 2)).reshape(3, 1)

These two arrays are quite straightforward, but keep in mind that in real-world applications, there might be two or more arrays which might represent more complex data, such as images, sensor readings, or other types of structured information.

Step 3: Using Hstack

Now that we have our arrays a and b ready, it's time to use hstack to combine the sequence horizontally. This is a simple process that aims to sequence horizontally column wise of the given arrays, as demonstrated by the following code:

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

The np.hstack() function takes a tuple of arrays that you want to concatenate horizontally. In this case, we are combining a and b to stack arrays in sequence horizontally. The result is a new array where the columns of b are added to the right of the columns of a.

Step 4: Let's Look at the Array formed

After performing the hstack operation, let's examine the resulting data.

print(result)

When we run this code snippet, we will see the following output array:

Output:

[[1. 1. 1. 2.]

 [1. 1. 1. 2.]

 [1. 1. 1. 2.]]

The output shows the merged array with the contents of both a and b arrays horizontally. The columns from b have been added to the right of the columns from a, effectively extending our dataset horizontally. Notice the resulting array does not have the same shape as the input arrays.

Dig deeper about NumPy with ProjectPro!

The numpy.hstack function in NumPy is a valuable tool for horizontally stacking or concatenating input arrays column wise. It is widely used in data science, machine learning, and scientific computing to manipulate and prepare for data analysis. By following the simple steps outlined in this guide, you can easily harness the power of hstack to merge and expand your data, making it ready for a wide range of applications. If you want to dive deeper into the applications part and are looking for a one-stop solution that has all the code along with guided videos, then check out ProjectPro. It offers subscription to a library of over 250 solved data science and big data projects and is an excellent platform to gain practical experience and excel in the two dynamic fields.

What Users are saying..

profile image

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Build Regression Models in Python for House Price Prediction
In this Machine Learning Regression project, you will build and evaluate various regression models in Python for house price prediction.

Topic modelling using Kmeans clustering to group customer reviews
In this Kmeans clustering machine learning project, you will perform topic modelling in order to group customer reviews based on recurring patterns.

Time Series Project to Build a Multiple Linear Regression Model
Learn to build a Multiple linear regression model in Python on Time Series Data

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

OpenCV Project to Master Advanced Computer Vision Concepts
In this OpenCV project, you will learn to implement advanced computer vision concepts and algorithms in OpenCV library using Python.

Build an AI Chatbot from Scratch using Keras Sequential Model
In this NLP Project, you will learn how to build an AI Chatbot from Scratch using Keras Sequential Model.

Many-to-One LSTM for Sentiment Analysis and Text Generation
In this LSTM Project , you will build develop a sentiment detection model using many-to-one LSTMs for accurate prediction of sentiment labels in airline text reviews. Additionally, we will also train many-to-one LSTMs on 'Alice's Adventures in Wonderland' to generate contextually relevant text.

Llama2 Project for MetaData Generation using FAISS and RAGs
In this LLM Llama2 Project, you will automate metadata generation using Llama2, RAGs, and AWS to reduce manual efforts.

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

Build a Multi ClassText Classification Model using Naive Bayes
Implement the Naive Bayes Algorithm to build a multi class text classification model in Python.