import geopandas as gpd from shapely.geometry import Polygon # Sample DataFrame with geometries (use your own data) data = {'ID': [1, 2, 3], 'geometry': [Polygon([(0, 0), (0, 2), (2, 2), (2, 0)]), Polygon([(2, 0), (2, 2), (4, 2), (4, 0)]), Polygon([(4, 0), (4, 2), (6, 2), (6, 0)])]} gdf = gpd.GeoDataFrame(data, crs="EPSG:4326") # Create a new column to store the neighboring IDs gdf['neighbors'] = None # Iterate through the GeoDataFrame to find neighbors for index, row in gdf.iterrows(): neighbors = [] for other_index, other_row in gdf.iterrows(): if index != other_index and row['geometry'].touches(other_row['geometry']): neighbors.append(other_row['ID']) gdf.at[index, 'neighbors'] = neighbors # Display the DataFrame with neighbors print(gdf[['ID', 'neighbors']]) def find_neighbors(geom_df): geom_df['neighbors'] = geom_df.apply(lambda row: find_single_neighbors(row, geom_df), axis=1) return geom_df def find_single_neighbors(row, geom_df): neighbors = [] for other_index, other_row in geom_df.iterrows(): if row.name != other_index and row['geometry'].touches(other_row['geometry']): neighbors.append(other_row['ID']) return neighbors # Example usage: # Replace 'your_data.geojson' with the path to your GeoJSON file or any other supported format # Make sure the GeoDataFrame has a 'geometry' column your_gdf = gpd.read_file('your_data.geojson') # Call the function to find neighbors result_gdf = find_neighbors(your_gdf) # Print the resulting GeoDataFrame print(result_gdf)