我正在尝试使用 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 中提取国家/地区。但是,我无法理解“以某种方式”。有什么想法吗?
请您参考如下方法:
使用map通过字典从 airports 创建 set_index与 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)
