ValueError: zero-dimensional arrays cannot be concatenated

31,406

concatenate turns each of the items in the list into an array (if it isn't already), and tries to join them:

In [129]: np.concatenate([1,2,3,4])
...

ValueError: zero-dimensional arrays cannot be concatenated

hstack takes the added step of: arrs = [atleast_1d(_m) for _m in tup], making sure they are at least 1d:

In [130]: np.hstack([1,2,3,4])
Out[130]: array([1, 2, 3, 4])

But the standard way of creating an array from scalars is with np.array, which joins the items along a new axis:

In [131]: np.array([1,2,3,4])
Out[131]: array([1, 2, 3, 4])

Note that np.array of 1 scalar is a 0d array:

In [132]: np.array(1)
Out[132]: array(1)

In [133]: _.shape
Out[133]: ()

If I want to join 4 0d arrays together, how long will that be? 4*0 =0? 4 1d arrays joined on their common axis is 4*1=4; 4 2d arrays (n,m), will be either (4n,m) or (n,4m) depending on the axis.


np.stack also works. It does something similar to:

In [139]: np.concatenate([np.expand_dims(i,axis=0) for i in [1,2,3,4]])
Out[139]: array([1, 2, 3, 4])
Share:
31,406
Simplicity
Author by

Simplicity

Updated on August 06, 2022

Comments

  • Simplicity
    Simplicity almost 2 years

    I have the following values, each of which is a scalar of type double: a1, a2, a3, a4, a5.

    I tried to concatenate them using Numpy, as follows:

    f = np.concatenate((a1,a2,a3,a4,a5))
    

    I however get the following error:

    ValueError: zero-dimensional arrays cannot be concatenated
    

    What could I be doing wrong?

    Thanks.