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

如何将Pandas DataFrame转换为Chart.js兼容的特定JSON格式

解决Pandas DataFrame转Chart.js兼容JSON的问题

我之前做可视化的时候刚好碰到过一模一样的需求,其实不用纠结Pandas内置的JSON导出函数,直接手动构建Chart.js需要的结构反而更灵活,给你一套简单的实现方案:

完整代码示例

import pandas as pd
import json

# 先构造你的示例DataFrame
data = {
    'month': ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월'],
    'order': [171, 72, 68, 84, 96, 58, 78, 67, 140, 124],
    'visit': [2042, 475, 405, 991, 684, 576, 671, 576, 1168, 837],
    'frequency': [8.4, 15.2, 16.8, 8.5, 14.0, 10.1, 11.6, 11.6, 12.0, 14.8]
}
df = pd.DataFrame(data)

# 构建Chart.js要求的JSON结构
chart_json = {
    # 提取月份作为横轴标签
    'labels': df['month'].tolist(),
    # 遍历需要的指标列,生成每个dataset对象
    'datasets': [
        {'label': column, 'data': df[column].tolist()}
        for column in ['order', 'visit', 'frequency']
    ]
}

# 输出JSON字符串(或保存到文件)
# 打印格式化后的JSON
print(json.dumps(chart_json, ensure_ascii=False, indent=2))

# 如果要直接保存到文件
with open('chart_data.json', 'w', encoding='utf-8') as f:
    json.dump(chart_json, f, ensure_ascii=False, indent=2)

关键步骤解释

  • 提取标签列:直接把month列转成列表,对应Chart.js里的labels字段,用来做横轴的月份标识
  • 生成数据集:用列表推导式遍历你需要的三个指标列,每个列自动生成包含label(列名)和data(列值列表)的字典,完美匹配Chart.js的datasets结构
  • JSON处理:用json.dumps(或json.dump)转成JSON时,ensure_ascii=False是为了保留韩语字符的正确显示,indent=2让JSON格式更清晰易读

运行这段代码后,生成的JSON完全符合你给出的目标格式,直接就能在Chart.js里使用啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:57:30