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

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python
In this machine learning regression project, you will learn to build NumPy Regression Models (Linear Regression, Ridge Regression, Lasso Regression) from Scratch.

End-to-End Speech Emotion Recognition Project using ANN
Speech Emotion Recognition using RAVDESS Audio Dataset - Build an Artificial Neural Network Model to Classify Audio Data into various Emotions like Sad, Happy, Angry, and Neutral

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Build a Customer Churn Prediction Model using Decision Trees
Develop a customer churn prediction model using decision tree machine learning algorithms and data science on streaming service data.

Ensemble Machine Learning Project - All State Insurance Claims Severity Prediction
In this ensemble machine learning project, we will predict what kind of claims an insurance company will get. This is implemented in python using ensemble machine learning algorithms.

MLOps Project on GCP using Kubeflow for Model Deployment
MLOps using Kubeflow on GCP - Build and deploy a deep learning model on Google Cloud Platform using Kubeflow pipelines in Python

Skip Gram Model Python Implementation for Word Embeddings
Skip-Gram Model word2vec Example -Learn how to implement the skip gram algorithm in NLP for word embeddings on a set of documents.