Numpy array concatenation error: 0-d arrays cannot be concatenated

I am trying to combine two numpy arrays, but I got this error. Can someone let me know a little what this really means?

Import numpy as np allValues = np.arange(-1, 1, 0.5) tmp = np.concatenate(allValues, np.array([30], float)) 

Then i got

 ValueError: 0-d arrays can't be concatenated 

If i do

  tmp = np.concatenate(allValues, np.array([50], float)) 

There is no error message, but the tmp variable also does not reflect concatenation.

+7
python arrays numpy concatenation
source share
2 answers

You need to put the arrays you want to combine into a sequence (usually a tuple or list) in the argument.

 tmp = np.concatenate((allValues, np.array([30], float))) tmp = np.concatenate([allValues, np.array([30], float)]) 

np.concatenate documentation for np.concatenate . Note that the first argument is the sequence (e.g. list, tuple) of the arrays. This does not take them as separate arguments.

As far as I know, this API is shared by all numpy concatenation functions: concatenate , hstack , vstack , dstack and column_stack all take one main argument, which should be some sequence of arrays.


The reason you get this particular error is because arrays are also sequences. But that means concatenate interprets allValues as a sequence of arrays for concatenation. However, each allValues element is a float, not an array, and therefore is interpreted as a zero-dimensional array. As stated in the error, these "arrays" cannot be combined.

The second argument is taken as the second (optional) argument to concatenate , which is the axis to concatenate. This only works because the second argument has one element that can be distinguished as a whole and therefore is a valid value. If you put an array with a large number of elements in the second argument, you would get another error:

 a = np.array([1, 2]) b = np.array([3, 4]) np.concatenate(a, b) # TypeError: only length-1 arrays can be converted to Python scalars 
+9
source share

Also make sure you combine the two numpy arrays. I concatenated one python array with a numpy array and it gave me the same error:

 ValueError: 0-d arrays can't be concatenated 

It took me a while to figure this out, since all the answers in stackoverflow suggested that you have two numpy arrays. Pretty stupid but easy to forget mistake. Therefore, the publication just in case helps someone.

Here are links to convert an existing python array using np.asarray or create np arrays if that helps.

+4
source share

All Articles