【问题标题】:Calculated column based on secondary key in Pandas Dataframe根据 Pandas Dataframe 中的辅助键计算列
【发布时间】:2022-01-06 11:58:09
【问题描述】:

我的数据看起来有点像这样:

key city currentCityKey
1 Boston NaN
2 New York 1
3 Concord 2

我想用当前城市名称创建一个新列,需要通过找到与 currentCityKey 值对应的城市来找到它,返回:

key city currentCityKey currentCity
1 Boston NaN NaN
2 New York 1 Boston
3 Concord 2 New York

我尝试了很多方法,但在尝试从 city 列返回值时遇到了问题。这应该只是一个简单的 if currentCityKey is notnull then city where currentCityKey == key,但我似乎无法从这个逻辑到实际代码。

原始输入:

df = pd.DataFrame({'key': [1, 2, 3],
 'city': ['Boston', 'New York', 'Concord'],
 'currentCityKey': [nan, 1.0, 2.0]})

【问题讨论】:

    标签: python pandas dataframe numpy


    【解决方案1】:

    使用'key''city' 列创建映射器,并在'currentCityKey' 列上使用map 以获得'currentCity' 列:

    df['currentCity'] = df['currentCityKey'].map(df.set_index('key')['city'])
    

    输出:

       key      city  currentCityKey currentCity
    0    1    Boston             NaN         NaN
    1    2  New York             1.0      Boston
    2    3   Concord             2.0    New York
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      相关资源
      最近更新 更多