Reputation: 2543
I have two arrays A
and B
,
>> np.shape(A)
>> (7, 6, 2)
>> np.shape(B)
>> (6,2)
Now, I want to concatenate the two arrays such that A
is extended to (8,6,2)
with A[8] = B
I tried np.concatenate()
>> np.concatenate((A,B),axis = 0)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-40-d614e94cfc50> in <module>()
----> 1 np.concatenate((A,B),axis = 0)
ValueError: all the input arrays must have same number of dimensions
and np.vstack()
>> np.vstack((A,B))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-41-7c091695f277> in <module>()
----> 1 np.vstack((A,B))
//anaconda/lib/python2.7/site-packages/numpy/core/shape_base.pyc in vstack(tup)
228
229 """
--> 230 return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
231
232 def hstack(tup):
ValueError: all the input arrays must have same number of dimensions
Upvotes: 2
Views: 10724
Reputation: 13465
Likely the simplest way is to use numpy newaxis like this:
import numpy as np
A = np.zeros((7, 6, 2))
B = np.zeros((6,2))
C = np.concatenate((A,B[np.newaxis,:,:]),axis=0)
print(A.shape,B.shape,C.shape)
, which results in this:
(7, 6, 2) (6, 2) (8, 6, 2)
As @sascha mentioned you can use vstack (also see hstack, dstack) to perform direct concatenation operations with an implicit axis (respectively axis = 0
, axis = 1
, axis =2
):
D = np.vstack((A,B[np.newaxis,:,:]))
print(D.shape)
, result:
(8, 6, 2)
Upvotes: 5