python3 dict ndarray 存成json,并保留原数据精度的实例

yipeiwu_com5年前Python基础

如下所示:

import numpy as np
import codecs, json 
 
a = np.arange(10).reshape(2,5) # a 2 by 5 array
b = a.tolist() # nested lists with same data, indices
file_path = "/path.json" ## your path variable
json.dump(b, codecs.open(file_path, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) ### this saves the array in .json format

关键是tolist和codecs编码,并转成适应json的格式。

解码并还原:

obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)

转自:https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable

以上这篇python3 dict ndarray 存成json,并保留原数据精度的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python判断字符串是否包含子字符串的方法

本文实例讲述了python判断字符串是否包含子字符串的方法。分享给大家供大家参考。具体如下: python的string对象没有contains方法,不用使用string.contain...

python开发之list操作实例分析

本文实例分析了python开发之list操作。分享给大家供大家参考,具体如下: 对python中list的操作,大家可以参考《Python list操作用法总结》 以下是我个人的笔记:...

Kali Linux安装ipython2 和 ipython3的方法

1、更新包管理 apt-get install update. 2、安装 pip3 :apt-get install python3-pip 3、安装ipython 2 : pip in...

python多线程之事件Event的使用详解

前言 小伙伴a,b,c围着吃火锅,当菜上齐了,请客的主人说:开吃!,于是小伙伴一起动筷子,这种场景如何实现 Event(事件) Event(事件):事件处理的机制:全局定义了一个内置标志...

PyTorch和Keras计算模型参数的例子

Pytorch中,变量参数,用numel得到参数数目,累加 def get_parameter_number(net): total_num = sum(p.numel() fo...