如何在vandas数据帧中将vincenty距离转换为float

我有分析vincenty距离的问题,因为格式是对象并且在那里有km度量,我想进一步分析.我想将vincenty距离转换为浮动格式

这是数据

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

这是我的代码

from geopy.distance import vincenty
df['vincenty_distance'] = df.apply(lambda x: vincenty((x['lat_free'], x['long_free']), (x['lat_device'], x['long_device'])), axis = 1)

这是结果

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

解决方法:

最好的是添加.km:

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

或者在处理后使用 – 转换为字符串,删除最后一个字母并转换为浮点数:

df['vincenty_distance'] = df['vincenty_distance'].astype(str).str[:-3].astype(float)
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

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...