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 以其简单易懂的语法格式与其它语言形成鲜明对比,初学者遇到最多的问题就是不按照 Python 的规则来写,即便是有编程经验的程序员,也容易按照固有的思维和语法格式来写...

在VS Code上搭建Python开发环境的方法

在VS Code上搭建Python开发环境的方法

1、下载安装 python https://www.python.org/downloads/windows/ web-based installer 在线安装 executable...

Python求算数平方根和约数的方法汇总

一、求算术平方根 a= x=int(raw_input('Enter a number:')) if x >= : while a*a < x: a = a + i...

numpy数组广播的机制

numpy数组广播的机制

numpy数组的广播功能强大,但是也同时让人疑惑不解,现在让我们来谈谈其中的原理。 广播原则: 如果两个数组的后缘维度(即:从末尾开始算起的维度)的轴长相符或其中一方的长度为1,则认为它...

详解Django解决ajax跨域访问问题

详解Django解决ajax跨域访问问题

这篇文章主要给大家介绍了关于Django跨域请求问题解决的相关资料,文中介绍的实现方法包括:使用django-cors-headers全局控制、使用JsonP,只能用于Get方法以及在v...