0

I am trying to concatenate two arrays: a and b, where

a.shape
(1460,10)
b.shape
(1460,)

I tried using hstack and concatenate as:

np.hstack((a,b)) 
c=np.concatenate(a,b,0) 

I am stuck with the error

 ValueError: all the input arrays must have same number of dimensions

Please guide me for concatenation and generating array c with dimensions 1460 x 11.

3 Answers 3

1

Try

b = np.expand_dims( b,axis=1 ) 

then

np.hstack((a,b))

or

np.concatenate( (a,b) , axis=1)

will work properly.

Sign up to request clarification or add additional context in comments.

Comments

1

np.c_[a, b] concatenates along the last axis. Per the docs,

... arrays will be stacked along their last axis after being upgraded to at least 2-D with 1's post-pended to the shape

Since b has shape (1460,) its shape gets upgraded to (1460, 1) before concatenation along the last axis.


In [26]: c = np.c_[a,b]

In [27]: c.shape
Out[27]: (1460, 11)

2 Comments

How can I store this array? Assignment does not work: it says "TypeError: 'CClass' object is not callable"
@optimist: Note that np.c_ is followed by brackets [...] rather than paretheses (...). The error 'CClass' object is not callable is saying that np.c_ can not be called, which is what happens when it is followed by parentheses.
1

The most basic operation that works is:

np.concatenate((a,b[:,None]),axis=1)

The [:,None] bit turns b into a (1060,1) array. Now the 1st dimensions of both arrays match, and you can easily concatenate on the 2nd.

There a many ways of adding the 2nd dimension to b, such as reshape and expanddims. hstack uses atleast_1d which does not help in this case. atleast_2d adds the None on the wrong side. I strongly advocate learning the [:,None] syntax.

Once the arrays are both 2d and match on the correct dimensions, concatenation is easy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.