我有一个熊猫数据框,其中有4列,分别代表2点(alpha和beta)的X和Y坐标。我想返回alpha和beta之间的欧几里得距离。
这是我的数据框:
alpha_x alpha_y beta_x beta_y
0 3.770047e+06 -1.933178e+07 3.771670e+06 -1.932118e+07
1 3.764890e+06 -1.927422e+07 3.759280e+06 -1.922667e+07
2 3.758185e+06 -1.922737e+07 3.758199e+06 -1.922815e+07
3 3.758748e+06 -1.923129e+07 3.758748e+06 -1.923129e+07
4 3.769639e+06 -1.934297e+07 3.770114e+06 -1.933611e+07
您可以使用以下代码加载它:
import pandas as pd
data =[[3770047.175941625, -19331776.34887237, 3771670.214117389, -19321175.08603543],
[3764889.7439331706, -19274223.583930705, 3759280.354792099, -19226669.81098408],
[3758184.9710026933, -19227374.77475073, 3758199.442536497, -19228148.049991384],
[3758748.247626108, -19231287.595948454, 3758748.247626108, -19231287.595948454],
[3769638.633410415, -19342974.05279793, 3770113.9676361005, -19336111.98073229]
]
dataframe = pd.DataFrame(data, columns = ['alpha_x', 'alpha_y', 'beta_x', 'beta_y'])
我尝试创建一个函数,以通过毕达哥拉斯方程为每一行运行各自的坐标,并将其返回到新创建的第5列[Distance]
def dist(row):
h = abs(dataframe['alpha_x']- dataframe['beta_x'])
v = abs(dataframe['alpha_y']- dataframe['beta_y'])
d = sqrt((h**2) + (v**2))
return d
dataframe["distance"] = dataframe.apply(lambda row: dist(row), axis = 1)
但是,该列未在我的df中创建,而是返回了SympifyError:
SympifyError: SympifyError: 0 1.150210e+08
1 2.292827e+09
2 5.981640e+05
3 0.000000e+00
4 4.731398e+07
dtype: float64
如果有人可以指导我解决我在这里做错的事情,我表示感谢。
答案 0 :(得分:0)
通过按行将进程从dataframe
替换为row
来更改功能:
def dist(row):
h = abs(row['alpha_x']- row['beta_x'])
v = abs(row['alpha_y']- row['beta_y'])
d = np.sqrt((h**2) + (v**2))
return d
dataframe["distance"] = dataframe.apply(lambda row: dist(row), axis = 1)
更好的解决方案,没有循环:
h = (dataframe['alpha_x'] - dataframe['beta_x']).abs()
v = (dataframe['alpha_y'] - dataframe['beta_y']).abs()
dataframe["distance1"] = np.sqrt((h**2) + (v**2))
print (dataframe)
alpha_x alpha_y beta_x beta_y distance \
0 3.770047e+06 -1.933178e+07 3.771670e+06 -1.932118e+07 10724.785623
1 3.764890e+06 -1.927422e+07 3.759280e+06 -1.922667e+07 47883.468630
2 3.758185e+06 -1.922737e+07 3.758199e+06 -1.922815e+07 773.410643
3 3.758748e+06 -1.923129e+07 3.758748e+06 -1.923129e+07 0.000000
4 3.769639e+06 -1.934297e+07 3.770114e+06 -1.933611e+07 6878.515513
distance1
0 10724.785623
1 47883.468630
2 773.410643
3 0.000000
4 6878.515513