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

如何使用Pola-rs将给定结构的DataFrame写入指定格式的JSON文件?

把Pola-rs DataFrame转成指定JSON格式的方法

步骤1:调整DataFrame的列结构

先把原DataFrame里的SkuId值包装成{"source": 对应值}的格式:

import polars as pl

df = pl.DataFrame([{"SkuId":1}])
# 给SkuId的值套上source结构
transformed_df = df.with_columns(
    pl.col("SkuId").map_elements(lambda x: {"source": x}, return_dtype=pl.Object)
)

步骤2:导出成目标JSON格式

Pola自带的JSON导出没法直接生成这种嵌套键值结构,所以先转成Python字典,再用标准库json写入文件:

import json

# 把DataFrame转成字典
result_dict = transformed_df.to_dict(as_series=False)
# 写入文件
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(result_dict, f, indent=2)

生成的output.json内容是:

{
  "SkuId": {
    "source": 1
  }
}

要是你就想要示例里带末尾逗号的格式,直接手动拼接写入就行:

with open("output.json", "w", encoding="utf-8") as f:
    f.write(f'"SkuId": {json.dumps(result_dict["SkuId"])},')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:52:11