[英]how vstack works according to numpy documentation
Python Beginner here. Python初学者在这里。
After going through numpy documentation which says vstack is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N).在通过 numpy 文档之后,它说 vstack 等效于在形状 (N,) 的一维数组被重新整形为 (1,N) 之后沿第一个轴的串联。
So the below code所以下面的代码
a = np.array([[1], [2], [3]])
b = np.array([[2], [3], [4]])
np.vstack((a,b))
should be应该
np.concatenate((a,b),axis=0))
After reshaping all 1-D arrays from (1,) to (1,1)将所有一维数组从 (1,) 重塑为 (1,1) 后
a will be将是
[[[1]]
[[2]]
[[3]]]
b will be b 将是
[[[2]]
[[3]]
[[4]]]
So,所以,
np.concatenate((a,b),axis=0)
should be应该
[[[1]]
[[2]]
[[3]]
[[2]]
[[3]]
[[4]]]
but the result shows但结果显示
[[1]
[2]
[3]
[2]
[3]
[4]]
Is there any misinterpretation from my side?我这边有什么误解吗? Please figure out where I am going wrong here?
请弄清楚我哪里出错了?
Here's the code:这是代码:
def vstack(tup):
arrs = np.atleast_2d(*tup)
if not isinstance(arrs, list):
arrs = [arrs]
return np.concatenate(arrs, 0)
So it just makes sure the input is a list of (atleast) 2d arrays, and does a concatenate on the first axis.所以它只是确保输入是一个(至少)二维数组的列表,并在第一个轴上进行连接。
Your arrays are already 2d, so it just does你的数组已经是二维的,所以它只是
In [45]: a = np.array([[1], [2], [3]])
...: b = np.array([[2], [3], [4]])
In [46]: a
Out[46]:
array([[1],
[2],
[3]])
In [47]: b
Out[47]:
array([[2],
[3],
[4]])
In [48]: np.concatenate((a,b), axis=0)
Out[48]:
array([[1],
[2],
[3],
[2],
[3],
[4]])
Your 'shouldbe'你的“应该”
In [49]: np.concatenate((a[...,None],b[...,None]), axis=0)
Out[49]:
array([[[1]],
[[2]],
[[3]],
[[2]],
[[3]],
[[4]]])
In [50]: _.shape
Out[50]: (6, 1, 1)
A case where the addition of a dimension matters, changing (3,) arrays to (1,3):添加维度很重要的情况,将 (3,) 数组更改为 (1,3):
In [51]: np.vstack((a.ravel(),b.ravel()))
Out[51]:
array([[1, 2, 3],
[2, 3, 4]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.