代码之家  ›  专栏  ›  技术社区  ›  Avenger

从列表映射数据帧中的列

  •  0
  • Avenger  · 技术社区  · 3 年前

    我有一个熊猫数据帧。

    is_active Device
    True       1
    False      2
    

    我有一个名为mapping.json的文件

    [
      {
        "description": "Desktop",
        "deviceId": "1"
      },
      {
        "description": "Smartphone",
        "deviceId": "2"
      },
      {
        "description": "Tablet",
        "deviceId": "3"
      }
    ]
    

    我需要从mapping.json中用设备id映射设备,以获得最终结果:

    is_active Device
    True       Desktop
    False      Smartphone
    

    我怎样才能用熊猫来实现它。 我正在做:

    with open('mapping.json', 'r') as file:
         c_map = json.load(file)
         output_df['Device'] = output_df['Device'].map(c_map)
    

    它给了我错误:TypeError:“list”对象不可调用

    1 回复  |  直到 3 年前
        1
  •  0
  •   mozway    3 年前

    你需要返工 cmap 成为一本字典:

    cmap = {d['deviceId']: d['description'] for d in cmap}
    

    然后 map 将按预期工作。