gpt4 book ai didi

python - Pandas 数据框到 JSON 的字典

转载 作者:太空狗 更新时间:2023-10-30 02:58:48 25 4
gpt4 key购买 nike

正如问题所问,我有一本我想保存的 pandas 的 dataframes 字典,这样下次我启动 ipython 时就不必重新采样数据了> 笔记本。我尝试了一些以前在其他情况下有效的简单方法:

import json
with open('result.json', 'w') as fp:
json.dump(d, fp)

但是我得到了这个错误:

[1001 rows x 6 columns] is not JSON serializable

我认为这与我的 pandas dataframe 有关,但我们将不胜感激。

最佳答案

您需要扩展 JSON 编码器,以便它知道如何序列化数据帧。示例(使用 to_json 方法):

import json
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_json'):
return obj.to_json(orient='records')
return json.JSONEncoder.default(self, obj)

保存:

with open('result.json', 'w') as fp:
json.dump({'1':df,'2':df}, fp, cls=JSONEncoder)

如果你愿意的话

json.load(open('result.json')

您将获得一本包含您的数据框的字典。您可以使用

加载它们
pd.read_json(json.load(open('result.json'))['1'])

关于python - Pandas 数据框到 JSON 的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com