Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: zero-dimensional arrays cannot be concatenated

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.

like image 505
Simplicity Avatar asked Jan 27 '18 00:01

Simplicity


1 Answers

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])
like image 64
hpaulj Avatar answered Nov 20 '22 07:11

hpaulj