Python 熊猫中坐标对之间的距离
查找此数据帧中给定点距离内的点(行)数的最佳方法是什么:Python 熊猫中坐标对之间的距离,python,pandas,scipy,Python,Pandas,Scipy,查找此数据帧中给定点距离内的点(行)数的最佳方法是什么: 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
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
)
df['points_in_3']=pd.DataFrame(squareform(pdist(df))。应用(
lambda x:x[x这是我使用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
从scipy.spatial.distance导入squareform,pdist
timeit df.apply(lambda x:sum((x-df)**2.sum(axis=1)**0.5)您在中看到距离矩阵函数了吗?