What is the usage of hstack in Python?

In Python, hstack is a function in the numpy library that is used to stack two arrays together along the horizontal axis (along the columns). Here is how it is used:

import numpy as np

# 创建两个数组
arr1 = np.array([[1, 2, 3],
                 [4, 5, 6]])

arr2 = np.array([[7, 8, 9],
                 [10, 11, 12]])

# 使用hstack函数将两个数组按水平方向堆叠起来
result = np.hstack((arr1, arr2))

print(result)

When running the above code, the output result will be:

[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]

It can be seen that arr1 and arr2 are stacked together horizontally, forming a new array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *