np.hstack:水平堆叠数组的方法

445 阅读2分钟

np.hstack - How to Stack Array in Horizontal Direction

np.hstack()是一个numpy 库函数,用于水平堆叠数组。Hstack代表水平堆叠。如果 使用hstack()函数将两个单维数组水平堆叠 ,得到的数组将是单维的 。 产生的数组先有数组1的元素,然后在最后附加上第二个数组的元素。这类似于连接轴为1的数组,这两者的结果是一样的。

语法

numpy.hstack(tup)

参数

tup:这是一个由数组组成的元组,我们要在其中执行hstack函数。在单维数组中,数组的长度可以不同,但在其他情况下,两个数组应该有相同的形状。

用于水平堆叠一维数组的Python程序

import numpy as np

# Creating an array named arr1
arr1 = np.array((1, 2, 3))

# Creating an array named arr2
arr2 = np.array((4, 5, 6))

# Printing the shape of the arr1
print(arr1.shape)

# Printing the shape of the arr2
print(arr2.shape)

# Creating the horizontally stacked array
res = np.hstack((arr1, arr2))
print(res)

输出

(3,)
(3,)
[1 2 3 4 5 6]

在这个程序中,我们导入了numpy来进行数值操作。首先,我们使用np.array() 创建了两个numpy数组。它创建了一个numpy数组。然后我们用np.shape 打印了两个numpy数组的形状。这将打印出两个数组的尺寸。

然后,我们使用hstack()函数将数组arr1ansarr2水平堆叠。它将arr1arr2水平连接起来。

用于水平堆叠二维数组的Python程序

# Importing Numpy as np
import numpy as np

# Creating an array named arr1
arr1 = np.array([[1, 2, 3], [4, 5, 6]])

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

# Printing the shape of the arr1
print(arr1.shape)

# Printing the shape of the arr2
print(arr2.shape)

# Creating the horizontally stacked array
res = np.hstack((arr1, arr2))
print(res)

输出

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

在这个程序中,我们创建了一个多维数组。我们已经打印了两个numpy数组的形状。最后,我们对这些多维数组进行了水平堆叠。

np.hstack()的教程就到此为止。