Sharki
Sharki

Reputation: 424

Numpy concatenate, using * or similar

I have a list of numpy arrays. Something like this (it won't be the same example, but similar)

lst = [np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1), np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1), np.array([ 1,2,3,4,5,6 ]).reshape(-1, 1)]

My lst in this case has 3 numpy arrays where their shape is (6,1), now I'd like to concatenate it, in something like this:

# array([[1, 1, 1],
#        [2, 2, 2],
#        [3, 3, 3],
#        [4, 4, 4],
#        [5, 5, 5],
#        [6, 6, 6]])

and this works perfectly doing this...

example = np.c_[lst[0], lst[1], lst[2]]

but my lst is not always the same size, so I tried this.

example = np.c_[*lst]

but it doesn't work. Is there any way to concatenete a whole list in this way?

Upvotes: 1

Views: 108

Answers (1)

ywbaek
ywbaek

Reputation: 3031

You can use column_stack function:

import numpy as np

lst = [np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1), np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1), np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1)]

example = np.column_stack(lst)
print(example)
[[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]
 [5 5 5]
 [6 6 6]]

Upvotes: 1

Related Questions