2016-12-18 95 views
2

我想分析一些與使用熊貓的航線有關的數據。所以,我有兩個dataframes:如何根據其他數據框中的列將值分配給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中提取。但是,我無法理解,「不知何故」。有任何想法嗎?

回答

2

使用map通過字典從airports通過set_indexto_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) 
相關問題