首页 > 解决方案 > 如何将(纬度,经度)字符串列转换为浮点列?

问题描述

我有一个显示时间和 GPS 坐标的数据框,如下所示:

2019-02-15 15:32:00 55.652480   12.510514

我需要将它提供给如下所示的函数:

import math

def haversine(coord1, coord2):
    R = 6372800  # Earth radius in meters
    lat1, lon1 = coord1
    lat2, lon2 = coord2

    phi1, phi2 = math.radians(lat1), math.radians(lat2) 
    dphi       = math.radians(lat2 - lat1)
    dlambda    = math.radians(lon2 - lon1)

    a = math.sin(dphi/2)**2 + \
        math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2

    return 2*R*math.atan2(math.sqrt(a), math.sqrt(1 - a))

for n in clean["gps"]:
    print(n)

    for city, coord in crimepoints.items():
        distance = haversine(n, coord)
        print(city, distance)
        if distance <= 500:
            print('alarm')
            print(distance)
            crimelist.append(city)
            crimelist.append(distance)

该函数接收如下所示的数据: coord = 51.5073219, -0.1276474 两个浮点数 所以我使用了这个:

clean["gps"] = clean["latitude"].map(str) + "," + " " + clean["longitude"].map(str)

2019-02-15 15:32:00 55.652480   12.510514   55.652480000000004, 12.510514

将纬度和经度放在一个变量中。问题是我现在无法将字符串转换为一个变量中的 2 个浮点数。我尝试了很多东西,例如 float()、ast.literal_eval()、map(float,test.split(',')),但没有结果。

我在收获函数中收到此错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-190-84732733cea4> in <module>
     44 
     45     for city, coord in crimepoints.items():
---> 46         distance = haversine(n, tok)
     47         print(city, distance)
     48         if distance <= 500:

<ipython-input-190-84732733cea4> in haversine(coord1, coord2)
      3 def haversine(coord1, coord2):
      4     R = 6372800  # Earth radius in meters
----> 5     lat1, lon1 = coord1
      6     lat2, lon2 = coord2
      7 

ValueError: too many values to unpack (expected 2)

标签: python-3.xstringgps

解决方案


在下面的代码中,我使用 float 辅助函数将 float 从包含在单个变量中的字符串转换:

sampleInp = "55.652480000000004, 12.510514"
def convert_float(inp):
    splitted_data = inp.split(",")
    return float(splitted_data[-2]), float(splitted_data[-1])
lat, long = convert_float(sampleInp)
print("Types : ",type(lat), type(long), "Values: ", lat, long)

输出:

Types :  <class 'float'> <class 'float'> Values:  55.652480000000004 12.510514

希望这可以帮助!!


推荐阅读