0

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:

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]?

1
  • use np.hstack Commented Dec 7, 2022 at 14:19

1 Answer 1

2

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.

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

3 Comments

Yes, thank you very much. Do you have an explanation though why np.append works when the length is the same and otherwise fails?
@Lars I resumed the problem in the EDIT
np.append is a poorly named cover for concatenate. It's ok for adding one value to a 1d array, for anything else use concatenate itself or one of the stack's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.