首页 > 解决方案 > 使用 Pandas 将数据帧作为 JSON 编码的字典写入文本文件

问题描述

我有一个包含 JSON 编码字典的大文本文件。

{"a": 10, "b": 11, "c": 12, "d": 13, "e": 14, "f": 15, "g": 16, "h": 17, "i": 18, "j": 19}
{"a": 20, "b": 21, "c": 22, "d": 23, "e": 24, "f": 25, "g": 26, "h": 27, "i": 28, "j": 29}
...

我使用 Pandas 是因为它允许我轻松地重命名和重新索引字典键。

with open("my_dictionaries.txt") as f:
    my_dicts = [json.loads(line.strip()) for line in f]

df = pd.Dataframe(my_dicts)
df.rename(columns= ...)
df.reindex(columns= ...)

现在我想将修改后的字典逐行写回文本文件,就像原始示例一样。我不想使用pd.to_csv(),因为我的数据有一些使 CSV 更难使用的怪癖。我一直在尝试pd.to_dict()andpd.to_json()方法,但有点卡住了。

有什么建议么?

标签: pythonpandas

解决方案


你可以使用这个:

import json

with open('output.txt', 'w') as f:
    for row in  df.to_dict('records'):
        f.write(json.dumps(row) + '\n')

或者:

import json

with open('output.txt', 'w') as f:
    f.writelines([(json.dumps(r) + '\n') for r in df.to_dict('records')])

推荐阅读