如何根据其他数据框中的列将值分配给 pandas 数据框中的列?

How to assign to values to column in pandas dataframe based on columns in other dataframe?

我正在尝试使用 pandas 分析一些与航线相关的数据。所以我有两个数据框:

print(airports.head())

           IATA/FAA           Country
Airport ID                           
1               GKA  Papua New Guinea
2               MAG  Papua New Guinea
3               HGU  Papua New Guinea
4               LAE  Papua New Guinea
5               POM  Papua New Guinea

print(routes.head())

        Source airport Destination airport
Airline                                   
2B                 AER                 KZN
2B                 ASF                 KZN
2B                 ASF                 MRV
2B                 CEK                 KZN
2B                 CEK                 OVB

现在我想在数据框 routes 中再添加两列:"SA country" 代表源机场的国家/地区,"DA country" 代表目的地机场的国家/地区。对于给定的 IATA/FAA,可以通过某种方式从数据框 airports 中提取国家/地区。但是,我无法理解 "somehow"。有什么想法吗?

使用map by dictionary creates from airports by set_index with to_dict,如果某些值不匹配得到NaN:

d = airports.set_index('IATA/FAA')['Country'].to_dict()
#works by map by Series but a bit slowier
#d = airports.set_index('IATA/FAA')['Country']
routes['SA country'] = routes['Source airport'].map(d)
routes['DA country'] = routes['Destination airport'].map(d)