在二维笛卡尔平面系统中,使用python计算数据框各个点之间的距离

问题描述 投票:0回答:1

我正在尝试创建一个新列,其中包含从第一个点到其余点的距离,但是出现错误。坐标是笛卡尔坐标系。

df = pandas.DataFrame({"X":[53100.6428, 46359.2159, 63286.7709, 178117.7184, 178041.0474], "Y":[32012.7328, 31168.1051, 1168.1051, -153941.4367, -157366.9088]})

df

>>> df
             X            Y
0   53100.6428   32012.7328
1   46359.2159   31168.1051
2   63286.7709    1168.1051
3  178117.7184 -153941.4367
4  178041.0474 -157366.9088

import math

df['Dist'] = math.sqrt(((df.loc[0, 'X']) - (df['X']))**2 + ((df.loc[0, 'Y']) - (df['Y']))**2)

>>> df['Distancia'] = math.sqrt(((df.loc[0, 'X']) - (df['X']))**2 + ((df.loc[0, 'Y']) - (df['Y']))**2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Laura\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\series.py", line 112, in wrapper
    raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'float'>

我该如何解决?有没有更好的方法?

谢谢! :)

python sqrt
1个回答
0
投票

这是解决方案-使用pow

first_x = df.loc[0, "X"]
first_y = df.loc[0, "Y"]

((df.X - first_x) ** 2 + (df.Y - first_y)).pow(.5)
© www.soinside.com 2019 - 2024. All rights reserved.