【发布时间】:2017-08-17 02:54:46
【问题描述】:
我在使用 zip(*map(...)) 调用时遇到错误。详细解释见下文。
TypeError: zip 参数 #1 必须支持迭代
这就是我得到的。包含城市及其经度和纬度位置的数据框。现在我想使用harversine formular 计算城市之间的距离。
起点是这个 Pandas DataFrame:
import pandas as pd
import numpy as np
df = pd.DataFrame([{'city':"Berlin", 'lat':52.5243700, 'lng':13.4105300},
{'city':"Potsdam", 'lat':52.3988600, 'lng':13.0656600},
{'city':"Hamburg", 'lat':53.5753200, 'lng':10.0153400}]);
df
然后我将数据框与自身连接以获得成对的城市:
df['tmp'] = 1
df2 = pd.merge(df,df,on='tmp')
df2 = df2[df2.city_x != df2.city_y]
这给了我这个:
city_x lat_x lng_x tmp city_y lat_y lng_y
1 Berlin 52.52437 13.41053 1 Potsdam 52.39886 13.06566
2 Berlin 52.52437 13.41053 1 Hamburg 53.57532 10.01534
3 Potsdam 52.39886 13.06566 1 Berlin 52.52437 13.41053
5 Potsdam 52.39886 13.06566 1 Hamburg 53.57532 10.01534
6 Hamburg 53.57532 10.01534 1 Berlin 52.52437 13.41053
7 Hamburg 53.57532 10.01534 1 Potsdam 52.39886 13.06566
现在让我们做重要的部分。将harversine公式放入函数中:
def haversine_distance(lng1: float, lat1: float, lng2: float, lat2: float) -> float:
"""
Computes the distance in kilometers between two points on a sphere given their longitudes and latitudes
based on the Harversine formula. https://en.wikipedia.org/wiki/Haversine_formula
"""
from math import radians, cos, sin, asin, sqrt
R = 6371 # Radius of earth in kilometers. Use 3956 for miles
lng1, lat1, lng2, lat2 = map(radians, [lng1, lat1, lng2, lat2])
# haversine formula
dlng = lng2 - lng1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlng/2)**2
c = 2 * asin(sqrt(a))
distance = c * R
return distance
然后应该在加入的数据帧上调用此函数:
def get_haversine_distance(lng1: pd.Series, lat1: pd.Series, lng2: pd.Series, lat2: pd.Series) -> pd.Series:
dist = zip(*map(haversine_distance, lng1, lat1, lng2, lat2))
return dist
# now invoke the method in order to get a new column (series) back
get_haversine_distance(df2['lng_x'], df2['lat_x'], df2['lng_y'], df2['lat_y'])
问题/错误:这给了我以下错误:
TypeError: zip 参数 #1 必须支持迭代
备注:我不明白的是,为什么我会收到错误,因为这种其他方法(见下文)工作得很好。基本一样!
def lat_lng_to_cartesian(lat: float, lng: float) -> float:
from math import radians, cos, sin
R = 6371 # Radius of earth in kilometers. Use 3956 for miles
lat_, lng_ = map(radians, [lat, lng])
x = R * cos(lat_) * cos(lng_)
y = R * cos(lat_) * sin(lng_)
z = R * sin(lat_)
return x, y, z
def get_cartesian_coordinates(lat: pd.Series, lng: pd.Series) -> (pd.Series, pd.Series, pd.Series):
if lat is None or lng is None:
return
x, y, z = zip(*map(lat_lng_to_cartesian, lat, lng))
return x, y, z
get_cartesian_coordinates(df2['lat_x'], df2['lng_x'])
【问题讨论】:
-
好的,试过了,但没用。 get_cartesian_coordinates 函数也可以在没有列表的情况下工作。
-
我不认为
map是这样工作的。理想情况下,您希望为可迭代的每个元素提供mapped函数。您需要做的是pd.Series的zip元素,然后将map与haversine_distance函数一起使用。 -
类似:
dist = pd.Series(map(lambda x: haversine_distance(*x), zip(lng1, lat1, lng2, lat2))). -
PS:为什么要投反对票?
-
似乎有人对所有内容都投了反对票。如果他们能让我们都知道问题及其答案有什么问题,那就太好了。
标签: python pandas dataframe zip-operator