问题是我有一个我想要保存的pandas数据帧字典,以便下次启动ipython笔记本时不需要对数据进行重新采样。我尝试过一些简单的东西,在以前的其他情况下也有用:
import json
with open('result.json', 'w') as fp:
json.dump(d, fp)
但我收到了这个错误:
[1001 rows x 6 columns] is not JSON serializable
我认为这与我的熊猫数据框有关,但是我们非常感谢任何帮助
答案 0 :(得分:6)
尽管上述方法可行,但是序列化的数据帧作为嵌入的字符串进入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
}
答案 1 :(得分:3)
您需要扩展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'])