Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy concatenate 2D arrays with 1D array

I am trying to concatenate 4 arrays, one 1D array of shape (78427,) and 3 2D array of shape (78427, 375/81/103). Basically this are 4 arrays with features for 78427 images, in which the 1D array only has 1 value for each image.

I tried concatenating the arrays as follows:

>>> print X_Cscores.shape (78427, 375) >>> print X_Mscores.shape (78427, 81) >>> print X_Tscores.shape (78427, 103) >>> print X_Yscores.shape (78427,) >>> np.concatenate((X_Cscores, X_Mscores, X_Tscores, X_Yscores), axis=1) 

This results in the following error:

Traceback (most recent call last): File "", line 1, in ValueError: all the input arrays must have same number of dimensions

The problem seems to be the 1D array, but I can't really see why (it also has 78427 values). I tried to transpose the 1D array before concatenating it, but that also didn't work.

Any help on what's the right method to concatenate these arrays would be appreciated!

like image 210
KCDC Avatar asked May 18 '15 13:05

KCDC


People also ask

How do you concatenate two arrays of different dimensions in Python?

You can either reshape it array_2. reshape(-1,1) , or add a new axis array_2[:,np. newaxis] to make it 2 dimensional before concatenation.

Can you concatenate NumPy arrays?

Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.

How do I concatenate two one direction arrays in Python?

Python NumPy concatenate arrays In numpy concatenate arrays we can easily use the function np. concatenate(). It can be used to concatenate two arrays either row-wise or column-wise. Concatenate function can take two or more arrays of the same shape and by default, it concatenates row-wise which means axis=0.


1 Answers

Try concatenating X_Yscores[:, None] (or X_Yscores[:, np.newaxis] as imaluengo suggests). This creates a 2D array out of a 1D array.

Example:

A = np.array([1, 2, 3]) print A.shape print A[:, None].shape 

Output:

(3,) (3,1) 
like image 161
Falko Avatar answered Sep 25 '22 09:09

Falko