Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two one-dimensional NumPy arrays

I have two simple one-dimensional arrays in NumPy. I should be able to concatenate them using numpy.concatenate. But I get this error for the code below:

TypeError: only length-1 arrays can be converted to Python scalars

Code

import numpy a = numpy.array([1, 2, 3]) b = numpy.array([5, 6]) numpy.concatenate(a, b) 

Why?

like image 999
highBandWidth Avatar asked Feb 11 '12 01:02

highBandWidth


People also ask

How do I combine two 1d arrays?

In numpy concatenate 1d arrays we can easily use the function np. concatenate(). In this method take two 1 dimensional arrays and concatenate them as an array sequence. So you have to pass arrays inside the concatenate function because concatenate function is used to join a sequence of arrays.

Can you concatenate NumPy arrays?

Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.


1 Answers

The line should be:

numpy.concatenate([a,b]) 

The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.

From the NumPy documentation:

numpy.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays together.

It was trying to interpret your b as the axis parameter, which is why it complained it couldn't convert it into a scalar.

like image 73
Winston Ewert Avatar answered Oct 03 '22 06:10

Winston Ewert