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])
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.
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With