4

In my Python program I concatenate several integers and an array. It would be intuitive if this would work:

x,y,z = 1,2,np.array([3,3,3])
np.concatenate((x,y,z))

However, instead all ints have to be converted to np.arrays:

x,y,z = 1,2,np.array([3,3,3])
np.concatenate((np.array([x]),np.array([y]),z))

Especially if you have many variables this manual converting is tedious. The problem is that x and y are 0-dimensional arrays, while z is 1-dimensional. Is there any way to do the concatenation without the converting?

1 Answer 1

7

They just have to be sequence objects, not necessarily numpy arrays:

x,y,z = 1,2,np.array([3,3,3])
np.concatenate(([x],[y],z))
# array([1, 2, 3, 4, 5])

Numpy also does have an insert function that will do this:

x,y,z = 1,2,np.array([3,3,3])
np.insert(z, [0,0], [x, y])

I'll add that if you're just trying to add integers to an list, you don't need numpy to do it:

x,y,z = 1,2,[3,3,3]
z = [x] + [y] + z

or

x,y,z = 1,2,[3,3,3]
[x, y] + z

or

x,y,z = 1,2,[3,3,3]
z.insert(0, y)
z.insert(0, x)
Sign up to request clarification or add additional context in comments.

1 Comment

Heh, this makes me feel a little bit stupid :). Thanks for your help. Now I also understand that there is a difference between ints/floats and sequence types like lists,tuples etc.

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.