pandas 坐标对之间的距离

Distances between coordinate pairs in pandas

在此 pandas 数据帧中查找给定点距离内的点(行)数的最佳方法是什么:

    x   y
0   2   9
1   8   7
2   1   10
3   9   2
4   8   4
5   1   1
6   2   3
7   10  5
8   6   6
9   9   7

结果(距离为 3)如下所示:

    x   y   points_within_3
0   2   9   1
1   8   7   4
2   1   10  1
3   9   2   3
4   8   4   5
5   1   1   1
6   2   3   1
7   10  5   4
8   6   6   2
9   9   7   4

更一般地说,我想了解如何使用 .transform().apply() 以这种方式比较行。 谢谢!

感谢@jme 的评论。

这个有效:

df['points_within_3'] = pd.DataFrame(squareform(pdist(df))).apply(
    lambda x: x[x<=3].count() - 1, axis=1
)

但这是最​​好的方法吗?

这就是我使用 lambda 表达式解决此问题的方法,但您可以看到 scipy 函数更快。

from scipy.spatial.distance import squareform, pdist

timeit df.apply(lambda x: sum(((x - df) ** 2).sum(axis=1) ** 0.5 <= 3) - 1, axis=1)
100 loops, best of 3: 5.34 ms per loop

timeit pd.DataFrame(squareform(pdist(df))).apply(lambda x: x[x<=3].count() - 1, axis=1)
100 loops, best of 3: 1.84 ms per loop