Python Beginner here.
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).
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)
a will be
[[[1]]
[[2]]
[[3]]]
b will be
[[[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):
In [51]: np.vstack((a.ravel(),b.ravel()))
Out[51]:
array([[1, 2, 3],
[2, 3, 4]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.