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 遍历目录(包括子目录)下所有文件的实例

如下所示: def list_all_files(rootdir): import os _files = [] list = os.listdir(rootdir) #列出文...

python 实现批量xls文件转csv文件的方法

引言:以前写的一个批量xls转csv的python简单脚本,用的是python2.7 #coding=utf-8 import os import time import loggi...

python+selenium select下拉选择框定位处理方法

一、前言 总结一下python+selenium select下拉选择框定位处理的两种方式,以备后续使用时查询; 二、直接定位(XPath) 使用Firebug找到需要定位到的元素,直接...

python队列queue模块详解

队列queue 多应用在多线程应用中,多线程访问共享变量。对于多线程而言,访问共享变量时,队列queue是线程安全的。从queue队列的具体实现中,可以看出queue使用了1个线程互斥锁...

基于Python打造账号共享浏览器功能

基于Python打造账号共享浏览器功能

本篇文章介绍的内容会涉及到以下知识: PyQt5的使用; Selenium的使用; 代理服务器的架设和使用; 一、账号限制之痛 在如今的互联网中,免费的信息和资源占据了很...