在 Python 中将字典与 DataFrame 列序列化为 JSON 文件
·
在 Python 中将字典与 DataFrame 列序列化为 JSON 文件
在数据分析工作中,我们经常需要将配置或中间结果保存为 JSON 文件,以便后续加载和复现计算环境。
但如果字典里包含了 pandas.DataFrame 或 Series,直接 json.dump() 会报错,因为这些对象并不是原生的 Python 类型。本文将介绍如何把这类数据转换为可序列化的格式,并最终保存到本地。
示例场景
假设我们有一个字典 config,其中包含了分析所需的参数信息和部分数据列:
config = {
'project_id': 'demo001',
'speed_col': 'speed',
'density_col': 'density',
'direction_col': 'direction',
'data': {
'time': df['time'],
'speed': df['speed'],
'direction': df['direction'],
'density': df['density']
}
}
如果直接执行 json.dump(config, f),会报错:
TypeError: Object of type Series is not JSON serializable
原因是 df['time'] 等都是 pandas.Series 对象,无法直接写入 JSON。
解决办法:转换为 Python 内置类型
常见做法是将 Series 转换为 列表(list),时间类型可以额外转成字符串,避免 JSON 无法解析时间戳。如下所示:
import json
config = {
'project_id': 'demo001',
'speed_col': 'speed',
'density_col': 'density',
'direction_col': 'direction',
'data': {
'time': df['time'].astype(str).tolist(), # 时间转成字符串列表
'speed': df['speed'].tolist(),
'direction': df['direction'].tolist(),
'density': df['density'].tolist()
}
}
# 保存为 JSON 文件
out_file = "config_demo.json"
with open(out_file, "w", encoding="utf-8") as f:
json.dump(config, f, ensure_ascii=False, indent=2)
print(f"配置已保存:{out_file}")
导出的 JSON 文件结构
示例输出(部分):
{
"project_id": "demo001",
"speed_col": "speed",
"density_col": "density",
"direction_col": "direction",
"data": {
"time": ["2021-01-01 00:00:00", "2021-01-01 00:10:00", "..."],
"speed": [5.1, 5.3, 4.9, "..."],
"direction": [120.2, 118.7, 121.0, "..."],
"density": [1.126, 1.126, 1.126, "..."]
}
}
注意事项
-
如果数据量很大(数万行以上),直接保存整个
data会让 JSON 文件体积膨胀。此时更好的做法是:- 只保存必要的配置(如列名、常数等),
- 或者将原始数据保存为 CSV/Parquet,再在 JSON 里保存文件路径。
-
如果只想保存“字段映射与参数配置”,可以将
data字段删除,仅保留project_id和列名配置。
总结
- 问题来源:
pandas.Series不能直接写入 JSON。 - 解决方法:使用
.tolist()转换为列表,时间列额外.astype(str)。 - 扩展思路:大数据量时,JSON 仅保存配置,原始数据单独存储。
这样,既能保证 JSON 文件结构清晰,又能避免体积过大。
更多推荐



所有评论(0)