kdtree
raw JSON → 0.16 verified Fri May 01 auth: no python maintenance
A Python implementation of a kd-tree for efficient spatial searching. Current version 0.16. Intermittent releases, last updated 2017.
pip install kdtree Common errors
error ModuleNotFoundError: No module named 'kdtree' ↓
cause The library is not installed.
fix
Run 'pip install kdtree'
error AttributeError: 'KDTree' object has no attribute 'search_nn' ↓
cause Method renamed in newer versions.
fix
Use 'search_nearest' instead of 'search_nn'.
error TypeError: __init__() takes at least 2 arguments (1 given) ↓
cause KDTree requires a list of points as argument.
fix
Create tree with points: tree = KDTree([(1,2), (3,4)])
Warnings
breaking The 'search_nn' method returns a single result in older versions; newer versions return a list. ↓
fix Upgrade to >=0.12 and use 'search_nearest' for consistent single-result behavior.
deprecated The 'add' method does not exist in v0.16; use the constructor to build the tree. ↓
fix Pass all points at construction time: KDTree(points).
gotcha Points must be tuples/lists of numbers; mixing types (e.g., int and float) is fine, but non-numeric types cause errors. ↓
fix Ensure all point coordinates are numeric (int or float).
Imports
- KDTree wrong
import kdtreecorrectfrom kdtree import KDTree - create
from kdtree import KDTree
Quickstart
from kdtree import KDTree
# Create a KDTree from a list of points (each point is a tuple)
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
tree = KDTree(points)
# Search for the nearest neighbor to a query point
query = (9, 2)
nearest = tree.search_nearest(query)
print(f'Nearest neighbor to {query}: {nearest}')