votes up 30

Only length-1 arrays can be converted to Python scalars

Package:
dask
github stars 8734
Exception Class:
TypeError

Raise code

else:
            return bool(self.compute())

    __nonzero__ = __bool__  # python 2

    def _scalarfunc(self, cast_type):
        if self.size > 1:
            raise TypeError("Only length-1 arrays can be converted to Python scalars")
        else:
            return cast_type(self.compute())

    def __int__(self):
        return self._scalarfunc(int)

    __long__ = __int__  # python 2

Ways to fix

votes up 1 votes down

This happens when casting a dask array of length greater than one to a python scalar type.

For example in the following sample code the array of floats is being converted to an integer scalar. But Since the length is greater than one then the exception is raised.

import dask.array as da
import numpy as np
x = da.from_array([-2.0, -1.0, 0, 1, 2], chunks=2)
int(x)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-7d1d15465d0b> in <module>()  2 import numpy as np  3 x = da.from_array([-2.0, -1.0, 0, 1, 2], chunks=2) ----> 4 int(x) 
/usr/local/lib/python3.7/dist-packages/dask/array/core.py in __int__(self)  1482   1483 def __int__(self): -> 1484 return self._scalarfunc(int)  1485   1486 __long__ = __int__ # python 2 
/usr/local/lib/python3.7/dist-packages/dask/array/core.py in _scalarfunc(self, cast_type)  1477 def _scalarfunc(self, cast_type):  1478 if self.size > 1: -> 1479 raise TypeError("Only length-1 arrays can be converted to Python scalars")  1480 else:  1481 return cast_type(self.compute()) 
TypeError: Only length-1 arrays can be converted to Python scalars

Fixed version of the code:

The array should have length = 1 to be casted to an integer scalar.

import dask.array as da
import numpy as np
x = da.from_array([-2.0])
print(int(x))

-2

Dec 30, 2021 kellemnegasi answer
kellemnegasi 22.6k

Add a possible fix

Please authorize to post fix