我正在尝试使用 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 国家”代表源机场的国家/地区,“DA 国家/地区”代表目的地机场的国家/地区。对于给定的 IATA/FAA
,可以通过某种方式从数据帧 airports
中提取国家/地区。但是,我无法理解“以某种方式”。有什么想法吗?
最佳答案
使用map
by 字典从 机场
创建 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)
关于python - 如何根据其他数据框中的列为 pandas 数据框中的列分配值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207249/