Thursday, December 3, 2020

Python Pool: Numpy Hstack in Python For Different Arrays

The numpy module in python consists of so many interesting functions. One such fascinating and time-saving method is the numpy hstack() function. Many times we want to stack different arrays into one array without losing the value. And that too in one line of code. So, to solve this problem, there are two functions available in numpy vstack() and hstack(). Here ‘v’ means ‘Vertical,’ and ‘h’ means ‘Horizontal.’

In this particular article, we will discuss in-depth the Numpy hstack() function. The numpy.hstack() function in Python is used to stack or pile the sequence of input arrays horizontally (column-wise) and make them a single array. You can use hstack() very effectively up to three-dimensional arrays. Enough talk now; let’s move directly to the usage and examples from the basics.

Syntax

numpy.hstack(tup)

Parameters

Name Description
tup The sequence of nd-array. The collection of input arrays is the only thing you need to provide as an input 

Note

We need only one argument for this function: ‘tup.’ Tup is known as a tuple containing arrays to be stacked. This parameter is a required parameter, and we have to mandatory pass a value.

Return Value

Stacked Array: The array (nd-array) formed by stacking the passed arrays.

Examples to Simplify Numpy Hstack

Now, we have seen the syntax, required parameters, and return value of the function numpy stack. Let’s move to the examples section. Here we will start from the very basic case and after that, we will increase the level of examples gradually.

Example 1: Basic Case to Learn the Working of Numpy Hstack

In this example 1, we will simply initialize, declare two numpy arrays and then make their horizontal stack using hstack function.

import numpy as np
x = np.array([0, 1, 2])
print ("First Input array : \n", x)  
y = np.array([3, 4, 5])
print ("Second Input array : \n", y)  
res = np.hstack((x,y))
print ("Horizontally stacked array:\n ", res) 

Output:

First Input array :
 [0 1 2]
Second Input array :
 [3 4 5]
Horizontally stacked array:
 [0 1 2 3 4 5]

Explanation:

In the above example, we stacked two numpy arrays horizontally (column-wise). Firstly we imported the numpy module. Following the import, we initialized, declared, and stored two numpy arrays in variable ‘x and y’. After that, with the np.hstack() function, we piled or stacked the two 1-D numpy arrays. Here please note that the stack will be done Horizontally (column-wise stack). Also, both the arrays must have the same shape along all but the first axis.

Example 2: Combining Three 1-D Arrays Horizontally Using numpy.hstack function

Let’s move to the second example here we will take three 1-D arrays and combine them into one single array.

import numpy as np
x = np.array([0, 1])
print ("First Input array : \n", x)  
y = np.array([2, 3])
print ("Second Input array : \n", y)  
z = np.array([4, 5])
print ("Third Input array : \n", z)  
res = np.hstack((x, y, z))
print ("Horizontally stacked array:\n ", res)

Output:

First Input array :
 [0 1]
Second Input array :
 [2 3]
Third Input array :
 [4 5]
Horizontally stacked array:
  [0 1 2 3 4 5]

Explanation

In the above example, we have done all the things similar to example 1 except adding one extra array. In example 1 we can see there are two arrays. But in this example, we have used three arrays ‘x, y, z’. And with the help of np.hstack() we joined them together column-wise (horizontally).

Example 3: Combining 2-D Numpy Arrays With Numpy.hstack

import numpy as np
x = np.array([[0, 1], [2, 3]])
print ("First Input array : \n", x)  
y = np.array([[4, 5], [6, 7]])
print ("Second Input array : \n", y) 
res = np.hstack((x, y))
print ("Horizontally stacked array:\n ", res)

Output:

First Input array :
 [[0 1]
 [2 3]]
Second Input array :
 [[4 5]
 [6 7]]
Horizontally stacked array:
 [[0 1 4 5]
 [2 3 6 7]]

Explanation:

In the above example, we have initialized and declared two 2-D arrays. And we have stored them in two variables, ‘x,y’ respectively. After storing the variables in two different arrays, we used the function to join the two 2-D arrays and make them one single 2-d array. Here we need to make sure that the shape of both the input arrays should be the same. If the shapes are different, then we will get a value error.

Example 4: Stacking 3-D Numpy Array using hstack Function

import numpy as np
x = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print ("First Input array : \n", x)  
y = np.array([[[9, 10], [11, 12]], [[13, 14], [15, 16]]])
print ("Second Input array : \n", y) 
res = np.hstack((x, y))
print ("Horizontally stacked array:\n ", res)

Output:

First Input array : 
 [[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
Second Input array : 
 [[[ 9 10]
  [11 12]]

 [[13 14]
  [15 16]]]
Horizontally stacked array:
  [[[ 1  2]
  [ 3  4]
  [ 9 10]
  [11 12]]

 [[ 5  6]
  [ 7  8]
  [13 14]
  [15 16]]]

Explanation

We can use this function for stacking or combining a 3-D array horizontally (column-wise). Instead of a 1-D array or a 2-D array in the above example, we have declared and initialized two 3-D arrays. After initializing, we have stored them in two variables, ‘x and y’ respectively. Following the storing part, we have used the function to stack the 3-D array in a horizontal manner (column-wise).

Note: The shape of the input arrays should be same.

Can We Combine Numpy Arrays with Different Shapes Using Hstack

The simple one word answer is No. Let’ prove it through one of the example.

import numpy as np
x = np.array([0, 1])
print ("First Input array : \n", x)  
y = np.array([3, 4, 5])
print ("Second Input array : \n", y)  
res = np.hstack((x,y))
print ("Horizontally stacked array:\n ", res) 

Output:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

Explanation:

In the above case we get a value error. Here firstly we have imported the required module. After that, we have initialized two arrays and stored them in two different variables. Here the point to be noted is that in the variable ‘x’ the array has two elements. But in the variable ‘y’ the array has three elements. So, we can see the shape of both the arrays is not the same. Which is the basic requirement, while working with this function. That’s why we get a value error.

Difference Between Np.Hstack() and Np.Concatenate()

NumPy concatenate is similar to a more flexible model of np.hstack. NumPy concatenate also unites together NumPy arrays, but it might combine arrays collectively either vertically or even horizontally. So NumPy concatenate gets the capacity to unite arrays together like np.hstack plus np.vstack. How np.concatenate acts depends on how you utilize the axis parameter from the syntax.

Difference Between numpy hstack() and vstack()

NumPy hstack and NumPy vstack are alike because they both unite NumPy arrays together. The significant distinction is that np.hstack unites NumPy arrays horizontally and np.vstack unites arrays vertically.

Aside from that however, the syntax and behavior is quite similar.

Do the Number of Columns and Rows Needs to Be Same?

Column: No, if you use NumPy hstack, the input arrays may have a different number of columns.
Rows: If you use NumPy hstack, the input arrays have to possess exactly the identical amount of rows.

Conclusion

In this article, we have learned, different facets like syntax, functioning, and cases of this hstack in detail. Numpy.hstack() is a function that helps to pile the input sequence horizontally so as to produce one stacked array. It can be useful when we want to stack different arrays into one column-wise (horizontally). We can use this function up to nd-arrays but it’s recommended to use it till
3-D arrays.

However, if you have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

The post Numpy Hstack in Python For Different Arrays appeared first on Python Pool.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...