2

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
4
  • 3
    Do this first before concat. Commented May 12, 2016 at 12:29
  • hey thanks, it worked :) first using expand_dims and then np.concatanate. btw what did you mean by use more expressive np.vstack then concat? Commented May 12, 2016 at 12:35
  • I didn't saw that you tried np.vstack too. In this case i would prefer vstack, because it needs no params and one can see whats happening immediatly. If you need to do this expand_dims stuff alot, you can also try the newaxis-approach (you only add indexing to B) mentioned in the docs. It's a bit shorter. Commented May 12, 2016 at 12:36
  • Your error message shows that vstack just hides some concatenate details. Commented May 12, 2016 at 17:31

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.