【问题标题】:Python: TypeError: zip argument #1 must support iterationPython:TypeError:zip 参数 #1 必须支持迭代
【发布时间】: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.Serieszip 元素,然后将maphaversine_distance 函数一起使用。
  • 类似:dist = pd.Series(map(lambda x: haversine_distance(*x), zip(lng1, lat1, lng2, lat2))).
  • PS:为什么要投反对票?
  • 似乎有人对所有内容都投了反对票。如果他们能让我们都知道问题及其答案有什么问题,那就太好了。

标签: python pandas dataframe zip-operator


【解决方案1】:

您的 haversine_distance 函数返回一个数字,但 zip 想要一个可迭代的,因此它失败并出现异常。

lat_lng_to_cartesian 有效,因为它返回一个可迭代的 3 元组。

您可以通过返回 1 元组来消除异常:

return (distance,)

但我看不出这样做的意义——实际上你根本不需要压缩:

def get_haversine_distance(lng1: pd.Series, lat1: pd.Series, lng2: pd.Series, lat2: pd.Series) -> pd.Series:
    dist = map(haversine_distance, lng1, lat1, lng2, lat2)
    return pd.Series(dist)

【讨论】:

  • 后一个工作正常。谢谢。以错误方式使用 zip 是我的错。
【解决方案2】:

正如我在 cmets 中提到的,为了能够以您定义的当前方式使用 haversine_distance,您需要在 mapping 之前先使用 zip 这些列。本质上,您需要编辑get_haversine_distance 函数以确保在将每个元组解压缩为haversine_distance 函数的参数之前,它是zipping 对应的行到元组中。以下是使用提供的数据的说明:

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

#       city       lat       lng  tmp
# 0   Berlin  52.52437  13.41053    1
# 1  Potsdam  52.39886  13.06566    1
# 2  Hamburg  53.57532  10.01534    1

# Make sure to reset the index after you filter out the unneeded rows
df['tmp'] = 1
df2 = pd.merge(df,df,on='tmp')
df2 = df2[df2.city_x != df2.city_y].reset_index(drop=True)

#     city_x     lat_x     lng_x  tmp   city_y     lat_y     lng_y
# 0   Berlin  52.52437  13.41053    1  Potsdam  52.39886  13.06566
# 1   Berlin  52.52437  13.41053    1  Hamburg  53.57532  10.01534
# 2  Potsdam  52.39886  13.06566    1   Berlin  52.52437  13.41053
# 3  Potsdam  52.39886  13.06566    1  Hamburg  53.57532  10.01534
# 4  Hamburg  53.57532  10.01534    1   Berlin  52.52437  13.41053
# 5  Hamburg  53.57532  10.01534    1  Potsdam  52.39886  13.06566

def get_haversine_distance(lng1: pd.Series, lat1: pd.Series, lng2: pd.Series, lat2: pd.Series) -> pd.Series:
    dist = pd.Series(map(lambda x: haversine_distance(*x), zip(lng1, lat1, lng2, lat2)))
    return dist


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


df2['distance'] = get_haversine_distance(df2['lng_x'], df2['lat_x'], df2['lng_y'], df2['lat_y'])

#     city_x     lat_x     lng_x  tmp   city_y     lat_y     lng_y    distance
# 0   Berlin  52.52437  13.41053    1  Potsdam  52.39886  13.06566   27.215704
# 1   Berlin  52.52437  13.41053    1  Hamburg  53.57532  10.01534  255.223782
# 2  Potsdam  52.39886  13.06566    1   Berlin  52.52437  13.41053   27.215704
# 3  Potsdam  52.39886  13.06566    1  Hamburg  53.57532  10.01534  242.464120
# 4  Hamburg  53.57532  10.01534    1   Berlin  52.52437  13.41053  255.223782
# 5  Hamburg  53.57532  10.01534    1  Potsdam  52.39886  13.06566  242.464120

如果这是您期望的输出结果,请告诉我。

【讨论】:

  • 完美。我觉得我还是不太习惯 zip 和 map 甚至 *map。
  • 非常好,加分1
【解决方案3】:

正如 Andrea 指出的那样,问题在于 haversine_distance 返回一个数字而不是迭代器。话虽这么说,您也可以使用apply 到df2:

df2.apply(lambda row: haversine_distance(row['lng_x'], row['lat_x'], row['lng_y'], row['lat_y']), axis=1)

【讨论】:

  • 没错,我之前也有过这段代码。我想性能也更好。但是,如果我将 harversine 方法添加到 utils 文件中,那么将函数语法与我原来的帖子中提到的系列参数一起使用会很酷。
猜你喜欢
  • 1970-01-01
  • 2012-12-12
  • 2016-03-11
  • 1970-01-01
  • 2021-07-02
  • 2020-10-27
  • 2021-11-30
  • 2015-06-01
  • 1970-01-01
相关资源
最近更新 更多