Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack numpy array shape for general arrays

Tags:

python

numpy

An example:

    >>> import numpy as np    
    >>> list = [1,2,3,4]
    >>> array = np.asarray(list)
    >>> np.shape(array)
    (4,)

Now say I want to process a general array and read the number of rows and columns into variables m and n respectively, I would do:

>>> m, n = np.shape(array)

But this results in the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

for the example above. In my example above I would have thought m=1 and n = 4 would instead have been an appropriate result. What am I missing?

like image 703
Dipole Avatar asked Jun 23 '26 15:06

Dipole


2 Answers

Your array has ndim=1, which means len(array.shape)==1. Thus, you cannot unpack the shape tuple as if it were of length==2.

To "stretch" your array to have 2dim in case it currently has fewer, use np.atleast_2d.

>>> x = np.arange(3.0)
>>> y = np.atleast_2d(x)
>>> y
array([[ 0.,  1.,  2.]])
>>> m, n = y.shape

BTW, list and array are not good names for variables in python.

like image 96
shx2 Avatar answered Jun 25 '26 03:06

shx2


You showed us that:

>>> np.shape(array)
    (4,)

that is, it is a single element tuple.

m, n = (4,)

produces the same error. There is one element in the tuple, so Python can only unpack it into 1 variable. This isn't a numpy issue. When doing this kind of unpacking, the numer of variables has to match the number of terms in the tuple (or list).

If you come from MATLAB you may expect all arrays to be 2d or larger. But in numpy, arrays can be 1d or even 0d (with shape ()). There are multiple of ensuring that your array has 2 dimensions - reshape, extra [], [None,...], np.atleast_2d.

like image 28
hpaulj Avatar answered Jun 25 '26 03:06

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!