Search code examples
scipypython-3.4kdtree

Error running SciPy KDTree example


With Scipy on Python 3.4, when I run the minimal KDTree example that is here:

from scipy import spatial
x, y = np.mgrid[0:5, 2:8]
tree = spatial.KDTree(zip(x.ravel(), y.ravel()))

I get this error:

File "C:/_work/kdtree.py", line 9, in <module>
tree = spatial.KDTree(zip(x.ravel(), y.ravel()))
File "C:\Python34\lib\site-packages\scipy\spatial\kdtree.py", line 229, in __init__
self.n, self.m = np.shape(self.data)
ValueError: need more than 0 values to unpack

What am I doing wrong? I have attempted using both with scipy 14.0 and 15.1


Solution

  • This is a bug in the docstring. The argument to KDTree must be "array_like", but in Python 3, the object returned by zip is not "array_like". You can change the example to

    tree = spatial.KDTree(list(zip(x.ravel(), y.ravel())))
    

    or, instead of using zip to create the input to KDTree, you can use, say, np.column_stack:

    x, y = np.mgrid[0:5, 2:8]
    xy = np.column_stack((x.ravel(), y.ravel()))
    tree = spatial.KDTree(xy)
    

    With either change, the rest of the example should work.