import numpy as np
from scipy.spatial import KDTree
import pandas as pd
# Create a random DataFrame
df = pd.DataFrame(np.random.rand(10, 2), columns=['x', 'y'])
# Create a KDTree using the x and y columns of the DataFrame
tree = KDTree(df[['x', 'y']])
# Calculate the nearest neighbors for each row
distances, indices = tree.query(df[['x', 'y']], k=2)
nearest_indices = indices[:, 1]
# Add a new column to the DataFrame with the nearest indices
df['nearest_index'] = nearest_indices
df