1

我有两个熊猫数据框,第一个包含城市及其各自的坐标,另一个包含机场及其坐标(下面的示例)。我想计算在给定城市的一定距离(测地线)内有多少机场,并将其作为城市数据框中的一列。这是数据框的负责人(机场然后是城市):

|                     Name                         |     IATA    |     City     |   Latitude   |  Longitude  |
|--------------------------------------------------|-------------|--------------|--------------|-------------|
| Hartsfield Jackson Atlanta International Airport |     ATL     |    Atlanta   |   33.636700  | -84.428101  |
| Los Angeles International Airport                |     LAX     |  Los Angeles |   33.942501  | -118.407997 |
| Chicago O'Hare International Airport             |     ORD     |    Chicago   |   41.978600  | -87.904800  |

|                  city                  |     city_lat     |     city_long     |     airports_80miles     |
|----------------------------------------|------------------|-------------------|--------------------------|
| Akron, OH Metro Area                   |     41.146639    |    -81.350110     |            0             |
| Albany, OR Metro Area                  |     44.488898    |    -122.537208    |            0             |
| Albany-Schenectady-Troy, NY Metro Area |     42.787920    |    -73.942348     |            0             |

这是要使用的简单函数:

def distance(origin, destination):
    lat1, lon1 = origin
    lat2, lon2 = destination
    radius = 6371 # km
    lat1 = math.radians(lat1)
    lat2 = math.radians(lat2)
    lon1 = math.radians(lon1)
    lon2 = math.radians(lon2)
    dlat = (lat2-lat1)
    dlon = (lon2-lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(lat1) \
        * math.cos(lat2) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = radius * c

    return d*0.62

我如何在每个城市应用这个距离函数,循环机场的数据框及其坐标?

提前致谢!

4

1 回答 1

0

使用apply函数两次:

假设机场数据框是df1,城市数据框是df2,阈值距离是 80。

threshold_distance = 80.0

df2["Airports_within_threshold"] = df2.apply(lambda x: 
                                         df1.apply(lambda y: 
                                                   distance((x["city_lat"], x["city_long"]),
                                                            (y["Latitude"],y["Longitude"])) 
                                                   < threshold_distance, axis = 1), 
                                         axis = 1).sum(axis = 1)
于 2018-12-28T06:59:54.527 回答