pandas 数据框到JSON的字典 [英] Dictionary of Pandas' Dataframe to JSON

查看:68
本文介绍了 pandas 数据框到JSON的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所问,我有一个要保存的大熊猫字典dataframes,这样下次我启动ipython笔记本时就不必对数据进行重新采样了.我尝试过一些简单的方法,该方法以前在其他情况下都可以使用:

As the question asks I have a dictionary of pandas' dataframes that I want to save so that I don't have to resample the data next time I start the ipython notebook. I tried something simple which has worked in other cases before:

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

但是我得到了这个错误:

But I got this error:

[1001 rows x 6 columns] is not JSON serializable

我认为这与我的熊猫dataframe有关,但是任何帮助将不胜感激.

I think this has something to do with my pandas dataframe, but any help would be much appreciated.

推荐答案

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

You need to extend the JSON encoder so it knows how to serialise a dataframe. Example (using to_json method):

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')

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

You will get a dictionary with your dataframes. You can load them using

pd.read_json(json.load(open('result.json'))['1'])

这篇关于 pandas 数据框到JSON的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆