python - 在 Pandas 中将数据框列表导出和导入为 json 文件
问题描述
Pandas 具有适用于单个数据框的 DataFrame.to_json 和 pd.read_json 函数。但是,我一直在尝试找到一种方法来将包含许多数据框的列表导出和导入单个 json 文件。到目前为止,我已经使用以下代码成功导出列表:
with open('my_file.json', 'w') as outfile:
outfile.writelines([json.dumps(df.to_dict()) for df in list_of_df])
这将创建一个 json 文件,其中所有数据帧都转换为 dicts。但是,当我尝试反向读取文件并提取我的数据框时,出现错误。这是代码:
with open('my_file.json', 'r') as outfile:
list_of_df = [pd.DataFrame.from_dict(json.loads(item)) for item in
outfile]
我得到的错误是: JSONDecodeError: Extra data
我认为问题在于我必须以某种方式在读取 json 文件的代码中包含与“writelines”相反的内容,即“readlines”,但我不知道该怎么做。任何帮助将不胜感激!
解决方案
通过使用writelines
您的数据并不是真正意义上的 Python 列表,这使得阅读它有点棘手。我建议改为这样写入您的文件:
with open('my_file.json', 'w') as outfile:
outfile.write(json.dumps([df.to_dict() for df in list_of_df]))
这意味着我们可以像简单地使用一样读取它:
with open('my_file.json', 'r') as outfile:
list_of_df = [pd.DataFrame.from_dict(item) for item in json.loads(outfile.read())]
推荐阅读
- c - 无法在centos 7上安装mysql2并出现libmysqlclient错误
- c# - 如何使用直线 C# 在基于 Web 的机器人中获取用户当前位置
- python - FileNotFoundError: [WinError 2] 系统找不到指定的文件 / tempfile
- python - 在多处理中按模块划分行
- specflow - 无法在 specflow 2.1.0 中添加或修改标签
- python - 如何使用 Selenium 和 Python 通过“onclick”找到并单击按钮?
- shell - windows10上gsh.exe下nmake的奇怪行为
- javascript - 带有搜索选项的jquery tablesorter在chrome中不起作用
- postgresql - 在 PostgreSQL 中处理子选择
- character-encoding - 在 powerdesigner 中显示描述