Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate multiple numpy arrays in one array?

Tags:

arrays

numpy

Assume I have many numpy array:

a = ([1,2,3,4,5])
b = ([2,3,4,5,6])
c = ([3,4,5,6,7])

and I want to generate a new 2-D array:

d = ([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]])

What should I code? I tried used:

d = np.concatenate((a,b),axis=0)
d = np.concatenate((d,c),axis=0)

It returns:

d = ([1,2,3,4,5,2,3,4,5,6,3,4,5,6,7])
like image 596
HAO CHEN Avatar asked Jun 13 '17 09:06

HAO CHEN


People also ask

How do I concatenate NumPy arrays column-wise?

In order to join NumPy arrays column-wise, we can also use the concatenate() function. In this case, however, we would use the axis=1 parameter, in order to specify that we want to join the arrays along the column axis.

How do you concatenate multiple arrays in Python?

In order to concatenate more than one array, you simply concatenate the array with the concatenation of all the previous arrays. Show activity on this post. Equivalent to np. concatenate(tup, axis=0) if tup contains arrays that are at least 2-dimensional.


1 Answers

As mentioned in the comments you could just use the np.array function:

>>> import numpy as np
>>> a = ([1,2,3,4,5])
>>> b = ([2,3,4,5,6])
>>> c = ([3,4,5,6,7])

>>> np.array([a, b, c])
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7]])

In the general case that you want to stack based on a "not-yet-existing" dimension, you can also use np.stack:

>>> np.stack([a, b, c], axis=0)
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7]])

>>> np.stack([a, b, c], axis=1)  # not what you want, this is only to show what is possible
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7]])
like image 51
MSeifert Avatar answered Oct 16 '22 16:10

MSeifert