【问题标题】:Is there any way to access the matrixes using the (x,y) as index有没有办法使用 (x,y) 作为索引来访问矩阵
【发布时间】:2020-08-10 18:32:22
【问题描述】:

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

如下图所示,我希望能够使用点作为索引来访问距离。

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

【问题讨论】:

  • 使用字典
  • 如果我没记错的话,你需要一个由最大坐标值定义的大小矩阵。在您的情况下,它将是一个 10x10 矩阵(对称)。这仅在您的坐标是正整数时才有效,如您的示例所示。对于任何其他情况,您需要某种映射数组 imo。

标签: python arrays matrix np


【解决方案1】:

一种解决方案是使用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

希望有帮助

【讨论】:

    【解决方案2】:

    如果你要求在 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]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多