Rchieve
Rchieve

Reputation: 13

Concatenate numpy arrays

I want to concatenate three 1 dimensional numpy arrays (x1, x2, x3) to one array X (3 columns). I already tried the concatenate function but I think I am doing something wrong. At least I got an error message:

I tried the following:

X = np.concatenate([x1, x2, x3], axis = 1)

As well as:

X = np.concatenate((x1, x2, x3), axis = 1)

Both times I got an error:

Error: IndexError: axis 1 out of bounds [0, 1)

How to use the concatenate function correct? Or is there a better way to do it?

Upvotes: 1

Views: 4520

Answers (4)

Epic Wink
Epic Wink

Reputation: 845

Numpy has a stack function (since NumPy 1.10). This allows you to concatenate along any dimension, as long as it makes sense (eg can't concatenate 1-d arrays along 3rd dimension).

For example, pairing up the elements of two 1-D arrays:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([-1, -2, -3, -4])
>>> np.stack((a, b), 1)
array([[ 1, -1],
       [ 2, -2],
       [ 3, -3],
       [ 4, -4]])

(Note the input argument is a tuple of np.arrays)

Upvotes: 0

hpaulj
hpaulj

Reputation: 231335

The correct way to use concatenate is to reshape the arrays so they are (n,1) 2d array. Here's what np.column_stack does

In [222]: x1=np.arange(3);x2=np.arange(10,13);x3=np.arange(20,23)
In [230]: ll=[x1,x2,x3]

In [231]: np.concatenate([np.array(i, copy=False, ndmin=2).T for i in ll], axis=1)

Out[231]: 
array([[ 0, 10, 20],
       [ 1, 11, 21],
       [ 2, 12, 22]])

Though I think this is more readable:

In [233]: np.concatenate([i[:,None] for i in ll],axis=1)
Out[233]: 
array([[ 0, 10, 20],
       [ 1, 11, 21],
       [ 2, 12, 22]])

np.vstack does

In [238]: np.concatenate([np.atleast_2d(i) for i in ll],axis=0)
Out[238]: 
array([[ 0,  1,  2],
       [10, 11, 12],
       [20, 21, 22]])

but in this case requires a further transpose to get columns.

Upvotes: 0

Francesco Nazzaro
Francesco Nazzaro

Reputation: 2916

You have to use numpy.vstack. Try:

import numpy as np

X = np.vstack([x1, x2, x3])

The size of x1, x2 and x3 must be the same.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249123

I'd do it this way:

np.column_stack((x1, x2, x3))

To me this is more expressive, does what you want, and has an intuitive name with one less argument required.

Upvotes: 4

Related Questions