如何将数据帧数据作为 json 非数组对象写入 json 文件?

How to write dataframe data into json file as json non array objects?

我在 Pandas 数据帧中有数据,我可以通过调用将数据帧数据写入 JSON 文件:

df.to_json('filepath', orient='records')

这会将数据作为 JSON 个对象的 数组 写入 json 文件。

[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]

我希望 json 文件中的数据如下所示,即只是逗号分隔的 JSON 对象 没有数组

{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}

非常感谢任何帮助。我是 python 的新手,找不到路。谢谢。

啊,所以你想要一个 JSON line 文件。你可以用类似的方式做到这一点。循环调用 to_dict 并写入文件。

with open('file.json', 'w') as f:
    for x in df.to_dict(orient='r'):
        f.write(json.dumps(x) + '\n')

或者,循环调用 to_json

with open('file.json', 'w') as f:
    for _, r in df.iterrows():
        r.to_json(f); f.write('\n')