问题描述
在此提供一些背景知识。 Numpy v1.16,Python 3.6.8。
Given a little background here. Numpy v1.16, Python 3.6.8.
然后运行以下代码:
import numpy as np
arr1 = np.repeat(True,20)
arr2 = np.repeat(np.arange(5),4)
X = np.vstack((arr1,
arr2
)).T
arr3 = np.repeat(True,20).T
arr4 = np.repeat(np.arange(5),4).T
Y = np.hstack((arr3,
arr4
))
结果是X.shape为(20,2)(正常),而Y.shape为(40,)异常。
The result is that X.shape is (20,2)(which is normal), but Y.shape is (40,) which is abnormal.
在数学上,X和Y应该是完全相同的矩阵,但在我的机器中不是。那我在这里想念什么?预先谢谢您
Mathematically X and Y are supposed to be the exact same matrix, but in my machine they aren't. So what am I missing here? Thank you in advance
推荐答案
转置一维数组,例如 arr3
而 arr4
返回一维数组,而不是二维数组。
Transposing 1-d arrays such as arr3
and arr4
returns a 1-d array, not a 2-d array.
np.repeat(True,5)
# returns:
array([ True, True, True, True, True])
np.repeat(True,5).T
# returns:
array([ True, True, True, True, True])
它不会产生新的轴。在移调之前,您需要这样做。
It does not produce a new axis. You need to do that before transposing.
要增加轴数,可以使用 np.newaxis
。
To increase the number of axes, you can use np.newaxis
.
a = np.repeat(True, 5)
a[:, np.newaxis]
# returns:
array([[ True],
[ True],
[ True],
[ True],
[ True]])
a[:, np.newaxis].T
# returns:
array([[ True, True, True, True, True]])
这篇关于NumPy hstack的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!