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

yipeiwu_com6年前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下载文件时显示下载进度的方法。分享给大家供大家参考。具体分析如下: 将这段代码放入你的脚本中,类似:urllib.urlretrieve(getFile, sa...

Python实现将HTML转成PDF的方法分析

Python实现将HTML转成PDF的方法分析

本文实例讲述了Python实现将HTML转成PDF的方法。分享给大家供大家参考,具体如下: 主要使用的是wkhtmltopdf的Python封装——pdfkit 安装 1. Instal...

python访问mysql数据库的实现方法(2则示例)

本文实例讲述了python访问mysql数据库的实现方法。分享给大家供大家参考,具体如下: 首先安装与Python版本匹配的MySQLdb 示例一 import MySQLdb co...

Python中的四种交换数值的方法解析

Python中的四种交换数值的方法解析

这篇文章主要介绍了Python中的四种交换数值的方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 交换两个变量的值方法,这个面试...

python 测试实现方法

 1)doctest 使用doctest是一种类似于命令行尝试的方式,用法很简单,如下 复制代码 代码如下:def f(n): """ >>> f(1) 1...