有什么方法可以使用 (x,y) 作为索引来访问矩阵

Is there any way to access the matrixes using the (x,y) as index

我想生成一个矩阵来存储每个点与其他每个点之间的距离。我希望能够使用两个坐标访问矩阵中的这个距离值。

如下图,我希望能够以点为索引来获取距离

矩阵[a点,b点] = 两点之间的距离

一种解决方案是使用 pandas 模块。

  • 您可以使用“点坐标”来定义列名和索引名。
  • 使用 scipy.spatial.distance.cdist
  • 填充数据
  • 使用df["[x, y]"]
  • 访问一个点的所有距离
  • 使用列iloc访问特定距离

完整代码+插图

# import modules
import pandas as pd
from scipy.spatial.distance import cdist

# input points
points = [[1, 2], [2, 3], [3, 4], [5, 6], [9, 10]]

# Create dataframe
df = pd.DataFrame(cdist(points, points),
     columns=[str(p) for p in points],
     index=[str(p) for p in points])
print(df)
#             [1, 2]    [2, 3]    [3, 4]    [5, 6]    [9, 10]
# [1, 2]    0.000000  1.414214  2.828427  5.656854  11.313708
# [2, 3]    1.414214  0.000000  1.414214  4.242641   9.899495
# [3, 4]    2.828427  1.414214  0.000000  2.828427   8.485281
# [5, 6]    5.656854  4.242641  2.828427  0.000000   5.656854
# [9, 10]  11.313708  9.899495  8.485281  5.656854   0.000000

# select column "[2, 3]"
print(df["[2, 3]"])
# [1, 2]     1.414214
# [2, 3]     0.000000
# [3, 4]     1.414214
# [5, 6]     4.242641
# [9, 10]    9.899495

# get distance between point [2 3] and [1 2]
print(df["[2, 3]"].loc["[1, 2]"])
# 1.4142135623730951

希望对您有所帮助

如果要求用numpy解决,可以使用where子句。这里有一个示例:

import numpy as np
X = np.array([[1,2],[2,3],[3,4],[5,6],[9,10]])
distance_matrix = np.zeros((X.shape[0],X.shape[0]))
# distance matrix
distance_matrix[np.where(X==[1,2])[0][0],np.where(X==[1,2])[0][0]] = 0
distance_matrix[np.where(X==[1,2])[0][0],np.where(X==[2,3])[0][0]] = np.linalg.norm(np.array([1,2]) - np.array([2,3]))
distance_matrix[np.where(X==[2,3])[0][0],np.where(X==[1,2])[0][0]] = np.linalg.norm(np.array([1,2]) - np.array([2,3]))