You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将DataFrame的Device列与JSON映射匹配?解决类型错误

解决Pandas映射JSON列表时的TypeError问题

错误原因

你遇到的TypeError: 'list' object is not callable,是因为json.load(file)读取出来的c_map是列表结构,而Pandas的Series.map()方法只接受两种输入:

  • 键值对形式的字典(用于直接映射)
  • 可调用对象(比如自定义函数)
    列表既不是字典也不是可调用对象,所以无法直接用于映射。

解决方法

把JSON中的列表转换成键为deviceId、值为description的字典,同时注意统一数据类型(你的DataFrame中Device是整数,JSON里的deviceId是字符串,必须匹配才能映射成功)。

完整代码示例

import pandas as pd
import json

# 假设你的DataFrame结构如下
output_df = pd.DataFrame({
    "is_active": [True, False],
    "Device": [1, 2]
})

# 读取JSON并转换为映射字典
with open('mapping.json', 'r') as file:
    device_list = json.load(file)
    # 将deviceId转为整数,匹配DataFrame里的Device列类型
    device_map = {int(item['deviceId']): item['description'] for item in device_list}

# 执行映射替换
output_df['Device'] = output_df['Device'].map(device_map)

print(output_df)

运行结果

is_active     Device
0       True    Desktop
1      False  Smartphone

另一种可选方案(转换DataFrame列类型)

如果不想修改字典的键类型,也可以把DataFrame的Device列转为字符串:

with open('mapping.json', 'r') as file:
    device_list = json.load(file)
    device_map = {item['deviceId']: item['description'] for item in device_list}

output_df['Device'] = output_df['Device'].astype(str).map(device_map)

内容的提问来源于stack exchange,提问作者Avenger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:52:20