Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array concatenation error: 0-d arrays can't be concatenated

I am trying to concatenate two numpy arrays, but I got this error. Could some one give me a bit clue about what this actually 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 tmp variable does not reflect the concatenation either.

like image 428
Bin Zhou Avatar asked Aug 22 '14 18:08

Bin Zhou


People also ask

What is concatenate in NumPy?

Numpy with Python Concatenation refers to joining. This function is used to join two or more arrays of the same shape along a specified axis.


2 Answers

You need to put the arrays you want to concatenate 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)])

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

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


The reason you are getting that particular error is that arrays are sequences as well. But this means that concatenate is interpreting allValues as a sequence of arrays to concatenate. However, each element of allValues is a float rather than an array, and is therefore being interpreted as a zero-dimensional array. As the error says, these "arrays" cannot be concatenated.

The second argument is taken as the second (optional) argument of concatenate, which is the axis to concatenate on. This only works because there is a single element in the second argument, which can be cast as an integer and therefore is a valid value. If you had put an array with more elements in the second argument, you would have gotten a different 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
like image 70
Roger Fan Avatar answered Oct 15 '22 04:10

Roger Fan


Also make sure you are concatenating two numpy arrays. I was concatenating one python array with a numpy array and it was giving me the same error:

ValueError: 0-d arrays can't be concatenated

It took me some time to figure this out since all the answers in stackoverflow were assuming that you had two numpy arrays. Pretty silly but easily overlooked mistake. Hence posting just in case this helps someone.

Here are the links to converting an existing python array using np.asarray or create np arrays, if it helps.

like image 27
mithunpaul Avatar answered Oct 15 '22 04:10

mithunpaul