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

pandas.Series.to_json内存泄漏问题排查及解决方案咨询

pandas.Series.to_json 内存泄漏问题排查与临时解决方案

问题背景

生产服务内存持续增长,经测试定位疑似pandas.Series.to_json方法导致内存泄漏。测试代码及输出如下:

测试代码

import pandas as pd
import gc
for i in range(0,10):
    series = pd.Series([0.008, 0.002])
    json_string = series.to_json(orient="records")
    _ = gc.collect()
    print("gc_count={}".format(len(gc.get_objects())))

输出结果

gc_count=46619
gc_count=46619
gc_count=46620
gc_count=46621
gc_count=46622
gc_count=46623
gc_count=46624
gc_count=46625
gc_count=46626
gc_count=46627

现象:前两次GC对象计数无变化,后续每次迭代计数递增1,说明存在未被回收的对象,确认内存泄漏。测试环境为Python 3.8、3.9。

解决方案

该问题属于pandas已知内部问题,临时替代方案是先将Series转为字典,再用标准库json模块完成序列化:

import pandas as pd
import json
import gc

for i in range(0,10):
    series = pd.Series([0.008, 0.002])
    json_string = json.dumps(series.to_dict(orient="records"))
    _ = gc.collect()
    print("gc_count={}".format(len(gc.get_objects())))

此方法可避免原to_json方法中的引用泄漏,确保对象能被GC正常回收。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:24:40