遍历两个Pandas数据框,并应用给定城市距离内的机场计数功能

时间:2018-12-28 04:04:49

标签: python pandas loops distance geodesic-sphere

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

|                     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

如何在每个城市上应用此距离函数,遍历机场及其坐标的数据框?

谢谢!

1 个答案:

答案 0 :(得分: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)