1

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?

1
  • Since they are 1d, there's no axis=1. You have to to turn the arrays into 2d first. That's what all the answers do before using concatenate. Commented Apr 29, 2016 at 13:37

4 Answers 4

4

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.

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

2 Comments

@Rchieve: if this solved your problem, you can "accept" this answer by clicking the checkmark on the left. Welcome to SO.
@ John Zwinck: Thanks for the hint! There was a 'delay'. I wasn't able to checkmark the answer during the first 10 minutes! Now it's done! (:
0

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.

1 Comment

You say hstack in one place but vstack in another. Which is it?
0

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.

Comments

0

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)

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.