Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

python - Dictionary of Pandas' Dataframe to JSON

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

Saving:

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

Now if you will do

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...