python - 使用 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()
方法,但有点卡住了。
有什么建议么?
解决方案
你可以使用这个:
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')])
推荐阅读
- javascript - 使用 Javascript 更改 CSS 规则
- nativescript - TypeError:无法读取未定义的属性“fromNativeSource”
- javascript - 如何使用 Ionic SQLite 转储/导出特定表?
- c - mvinnstr 返回一个带有 ncurses 的空字符串,而不是该行
- python - 取数据框中每一行的 predict_proba 的最大值
- python - Python SyntaxError:无法分配给运算符
- java - 当我在mybatis中使用insert、update(DML statements)时,如何确定它们执行成功?
- regex - RegEx 不验证没有第一个零的十进制数
- php - 为什么我的 $items 没有一组 $item?Laravel 8 电子商务
- performance - 为什么在测试具有特定类型签名的 Functor 实例时 QuickCheck 需要很长时间?