如何将行索引均为input的DataFrame转为每行带input键的jsonl文件
pandas 批量导出带外层
input键的jsonl文件解决方案 你可以直接通过给每行记录套外层结构的方式实现需求,无需调整现有重复索引,以下是两种可行实现:
方法1:手动包装记录后写入(逻辑清晰,兼容性好)
import json import pandas as pd # 可选:如果需要数值字段转为字符串格式,先执行类型转换 df1["item quantity"] = df1["item quantity"].astype(str) # 1. 把DataFrame每行转为字典 row_dicts = df1.to_dict("records") # 2. 给每行字典套外层input键 wrapped_rows = [{"input": row} for row in row_dicts] # 3. 写入jsonl文件 with open("shopify_import.jsonl", "w", encoding="utf-8") as f: for item in wrapped_rows: json.dump(item, f, ensure_ascii=False) f.write("\n")
方法2:借助pandas原生to_json方法(代码更简洁)
import pandas as pd df1["item quantity"] = df1["item quantity"].astype(str) # 构造单列,每一行的值就是原行对应的字典 df1["input"] = df1.to_dict("records") # 仅导出input列,直接生成符合要求的jsonl df1[["input"]].to_json( "shopify_import.jsonl", orient="records", lines=True, force_ascii=False )
额外说明
你之前用orient="index"报错是正常的,该参数要求DataFrame索引值唯一,你的所有行索引都是input不符合要求,该场景下不需要使用这个参数。
内容的提问来源于stack exchange,提问作者JJasperr
相关产品推荐
相关产品推荐

