【问题标题】:How to assign to values to column in pandas dataframe based on columns in other dataframe?如何根据其他数据框中的列为熊猫数据框中的列分配值?
【发布时间】:2016-12-18 09:59:10
【问题描述】:

我正在尝试使用 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 中提取国家/地区。但是,我无法理解“不知何故”。有什么想法吗?

【问题讨论】:

    标签: python python-3.x pandas multiple-columns


    【解决方案1】:

    使用map 由字典从airportsset_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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-21
      • 2019-12-09
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2023-03-17
      相关资源
      最近更新 更多