A k-d tree, used here through scikit-learn’s KDTree, organizes location points so a nearest-point search can avoid comparing every accommodation with every venue. It supports efficient multidimensional nearest-neighbor queries when geographic proximity must become usable tabular features. section 7.1.3
Nearest facilities for property listings
For each venue category—convenience stores, train stations, airports, bus stations, and subways—fit a KDTree on venue latitude and longitude. Query every listing with k=1, use Manhattan distance, convert the returned degree distances to meters, and store one nearest-distance column per category in a DataFrame for modeling. section 7.1.3
Listing 7.6 Finding the nearest facilities and transportation
from sklearn.neighbors import KDTree
relevant_spots = pd.read_csv("relevant_spots_Tokyo.csv")
venue_categories = ['Convenience Store', 'Train Station',
'Airport', 'Bus Station', 'Subway']
min_distances = {'listing_id': summary_listings['id']} #1
for venue in venue_categories:
venue_filter = relevant_spots['venueCategory'] == venue
venues = relevant_spots[
['latitude', 'longitude']
][venue_filter] #2
tree = KDTree(venues, metric='manhattan') #3
distance, index = tree.query(
summary_listings[['latitude', 'longitude']],
k=1
) #4
min_distances[
'nearest_' +
venue.lower().replace(" ", "_")
] = degrees_to_meters(
np.ravel(distance),
summary_listings['latitude']
)
min_distances = pd.DataFrame(min_distances) #5
This listing shows the operational pattern: filter each venue type, construct a KDTree from its coordinates, query all listing coordinates, and save the minimum distances as predictors. section 7.1.3
The same nearest-area lookup can stabilize geographic groups before validation. Compute each neighborhood’s mean coordinates, separate neighborhoods with fewer than 30 listings from larger ones, then query a KDTree built from the larger areas to map each small area to its nearest larger neighborhood. section 7.2.1


