如何在pandas datafram中将vincenty距离转换为float

2024-04-23 07:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在分析vincenty距离时遇到了问题,因为格式是object,其中有{}度量,我想进一步分析。我想把vincenty距离转换成float格式

这是数据

customer_id lat_free    long_free   lat_device  long_device radius      timestamp
7509        -6.283468   106.857636  -7.802388   110.368660  1264.000000 2017-12-14 21:18:40.327
7509        -6.283468   106.857636  -7.804296   110.367192  14.000000   2017-12-15 20:02:21.923

这是我的密码

^{pr2}$

这就是结果

customer_id lat_free    long_free   lat_device  long_device radius      timestamp                 Vincenty_distance
7509        -6.283468   106.857636  -7.802388   110.368660  1264.000000 2017-12-14 21:18:40.327   422.7123873310482 km
7509        -6.283468   106.857636  -7.804296   110.367192  14.000000   2017-12-15 20:02:21.923   422.64674499172787 km

我需要把Vincenty_distance转换成float


Tags: idfree距离device格式customerfloattimestamp
2条回答

您可以使用str.replace删除“km”,并使用apply将float设置为序列。在

例如:

df["Vincenty_distance"] = df["Vincenty_distance"].str.replace(" km", "").apply(float)

最好的方法是添加.km

df['Vincenty_distance'] = df.apply(lambda x: vincenty((x['lat_free'], x['long_free']), (x['lat_device'], x['long_device'])).km, axis = 1)

或在处理后使用-转换为string,删除最后一个字母并转换为floats:

^{pr2}$
print (df)
   customer_id  lat_free   long_free  lat_device  long_device  radius  \
0         7509 -6.283468  106.857636   -7.802388   110.368660  1264.0   
1         7509 -6.283468  106.857636   -7.804296   110.367192    14.0   

                 timestamp  Vincenty_distance  
0  2017-12-14 21:18:40.327         422.712361  
1  2017-12-15 20:02:21.923         422.646709  

print (df.dtypes)

customer_id            int64
lat_free             float64
long_free            float64
lat_device           float64
long_device          float64
radius               float64
timestamp             object
Vincenty_distance    float64
dtype: object

相关问题 更多 >