如何在Pandas中生成城市间欧氏距离交叉表
To generate the desired Euclidean distance cross table from your city coordinate data, follow these straightforward steps:
1. Set Up the Initial DataFrame
First, create a Pandas DataFrame using your city longitude and latitude values, with city names as the index for easy labeling later:
import pandas as pd # Create the coordinate DataFrame city_data = { 'City': ['A', 'B', 'C'], 'Longitude': [2, 5, 8], 'Latitude': [2, 6, 10] } df = pd.DataFrame(city_data).set_index('City')
2. Calculate Pairwise Euclidean Distances
The Euclidean distance between two points ((x_1, y_1)) and ((x_2, y_2)) is defined by this formula:
[ \text{Distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} ]
You can compute the full distance matrix using either of these methods:
Method 1: Use SciPy's Built-in Distance Function
This is the simplest approach, leveraging SciPy's optimized distance_matrix function:
from scipy.spatial import distance_matrix # Compute the distance matrix and format as a DataFrame distance_table = pd.DataFrame( distance_matrix(df.values, df.values), index=df.index, columns=df.index ).astype(int) # Convert to integer to match your expected output print(distance_table)
Method 2: Manual Formula Implementation
If you want to directly apply the Euclidean formula without external libraries:
# Extract coordinates as a numpy array coords = df.to_numpy() # Calculate pairwise distances using the Euclidean formula pairwise_distances = ((coords[:, None] - coords) ** 2).sum(axis=2) ** 0.5 # Convert to labeled DataFrame distance_table = pd.DataFrame(pairwise_distances, index=df.index, columns=df.index).astype(int) print(distance_table)
3. Final Output
Both methods will produce your desired cross table:
A B C City A 0 5 10 B 5 0 5 C 10 5 0
The .astype(int) step is optional but ensures integer values, which aligns with your example's whole-number distances.
内容的提问来源于stack exchange,提问作者Nabih Bawazir

