gpt4 book ai didi

python - 需要将一维数组转换为二维数组才能连接背后的逻辑是什么?

转载 作者:行者123 更新时间:2023-12-01 03:45:11 24 4
gpt4 key购买 nike

为了将一维数组连接到二维数组,建议进行以下修复:

A = np.array([1, 2, 3])
B = np.array([[4, 5],[6,7],[8,9]])

# np.hstack((A,B))
# throws "ValueError: all the input arrays must have same number of dimensions"

np.hstack((A[:, None],B)) #works

有人可以解释一下这背后的逻辑吗? (有链接吗?)

对于具有 matlab 背景的人来说,这个要求是不直观的。

谢谢!

最佳答案

hstack()的文档:

numpy.hstack(tup)[source] Stack arrays in sequence horizontally (column wise).

Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by hsplit.

Parameters: tup : sequence of ndarrays All arrays must have the same shape along all but the second axis. Returns: stacked : ndarray The array formed by stacking the given arrays.

ndarrays 序列除了第二个轴之外,所有数组都必须具有相同的形状。

A[:, None] 创建一个形状为 (3, 1) 的新数组,它是一个与 B 一样的二维数组,所以hstack() 有效。

您可以使用:

np.c_[A, B]
np.column_stack((A, B))

关于python - 需要将一维数组转换为二维数组才能连接背后的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39049028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com