Python numpy 快速数组计算到二维数组(矩阵)

Python numpy Quick Array Calculations to 2D Array (matrix)

我有一个用例,我有一组数千个坐标,我想对它们进行矢量化并将它们转换为距离。我想以这样的方式完成此操作,即我最终得到一个二维数组,实际上是一个矩阵,即 n x n,为我提供输入点之间的范数。我知道我会在对角线上有一堆零,这很好。我想尽快处理它。

目前我的方法是取一个 numpy 坐标数组,x,y,z 是一行,而列表是从文件中加载的许多元素,例如 5000 行。

我目前正在循环遍历坐标列表:

for i in range(n):
    for j in range(n):
        dist[i,j] = round(numpy.linalg.norm(coords[i] - coords[j]), 3)

dist 是一个带有 numpy.zeros((n,n)) 的 numpy 数组设置,其中我已经得到了 n 值,即坐标列表的长度。

我知道一定有一种更快的方法可以在此数据集上使用 numpy,当然是将坐标设为数组,我只是不确定如何有效地执行此操作。我想这样做的部分原因是我打算使用 truth table 掩码来进行数据处理。谢谢!

所以解决方法和上面说的一样简单,只需要导入scipy,然后使用:

distances = scipy.spatial.distance.cdist(coords, coords)

生成的数组是欧氏范数的 n x n 数组。

从scipy获得相同答案的另一种类似方式:

from scipy.spatial.distance import pdist, squareform

distances = squareform(pdist(coords))