Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy append multiple arrays

In R it is very easy to combine multiple vectors, for instance:

a<-c(1,2,3)
b<-c(4,5,6,7)
c<-c(8,9,10)
#combine to
d<-c(a,b,c)

This is what I want to recreate by using NumPy.

I tried to achieve this using np.append, and it works fine as long as all arrays have the same length, for instance:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
d = np.append(a,(b,c)) #works fine

However

a = np.array([1,2,3])
b = np.array([4,5,6,7])
c = np.array([8,9,10])
d = np.append(a,(b,c)) #does not work fine

The result is: [1,2 3 array([4,5,6,7]) array([8,9,10])]. How do I turn this into a classic NumPy array [1 2 3 4 5 6 7 8 9 10]?

>Solution :

I think you need this function:

np.concatenate([a,b,c])

am I right?

np.concatenate is used to concatenate arrays with same number of dimension, but different size, along one specific axis (0 axis by default). In your case, since you have just one dimension and you want to concatenate on the unique dimension you have, you can also use np.hstack([a,b,c]), as mentioned by @Sembei Norimaki in the comments.

EDIT to answer you question in the comments:

in the source code of numpy:

if axis is None:
    if arr.ndim != 1:
        arr = arr.ravel()
    values = ravel(values)
    axis = arr.ndim-1
return concatenate((arr, values), axis=axis)

as you can see, the values to append are forced to be a numpy array before appending them (this happens in the ravel function). Since your arrays have different shape, it is not possible to cast them in an integers numpy array and so a numpy array of numpy arrays is created (try np.array((b,c)) and see what happens). For this reason your are appending a numpy array of numpy arrays to an integer numpy array and this causes the problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading