【问题标题】:Dictionary of Pandas' Dataframe to JSONPandas 数据框到 JSON 的字典
【发布时间】:2023-03-13 12:39:01
【问题描述】:

正如问题所问,我有一本熊猫的字典 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 有关,但我们将不胜感激。

【问题讨论】:

  • 为什么不使用 HDFStore?

标签: python json pandas


【解决方案1】:

虽然上述方法有效,但序列化的数据帧作为嵌入字符串进入 json。如果你想要漂亮的 json,首先将数据帧转换为字典,然后使用普通的 json 接口编写。从磁盘读取后,您将转换回数据帧:

# data is dictionary of dataframes

import json

# convert dataframes into dictionaries
data_dict = {
    key: data[key].to_dict(orient='records') 
    for key in data.keys()
}

# write to disk
with open('data_dict.json', 'w') as fp:
    json.dump(
        data_dict, 
        fp, 
        indent=4, 
        sort_keys=True
    )

# read from disk
with open('data_dict.json', 'r') as fp:
    data_dict = json.load(fp)

# convert dictionaries into dataframes
data = {
    key: pd.DataFrame(data_dict[key]) 
    for key in data_dict
}

【讨论】:

  • 如果dataframe有TimeStamp对象,会报错TypeError: Object of type Timestamp is not JSON serializable
【解决方案2】:

您需要扩展 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'])

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 2013-09-12
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2018-05-04
    相关资源
    最近更新 更多