使用simplejson序列化numpy数组最有效的方法是什么?
发布于 2010-08-16 04:00:29
我会使用simplejson.dumps(somearray.tolist())作为最方便的方法(如果我还在使用simplejson,这意味着使用Python2.5或更早的版本;2.6和更高版本有一个标准库模块json,它以同样的方式工作,所以如果正在使用的Python发行版支持它,我当然会使用它;-)。
为了追求更高的效率,您可以子类化json.JSONEncoder (在json中;我不知道旧的simplejson是否已经提供了这样的定制可能性),并在default方法中,通过将numpy.array的特殊情况实例“及时”转换为列表或元组,将它们子类化。不过,我有点怀疑您是否能通过这样的方法在性能方面获得足够的收益来证明所做的努力是合理的。
发布于 2014-06-24 05:46:30
为了保持数据类型和维度,请尝试以下命令:
import base64
import json
import numpy as np
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
"""If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded.
"""
if isinstance(obj, np.ndarray):
if obj.flags['C_CONTIGUOUS']:
obj_data = obj.data
else:
cont_obj = np.ascontiguousarray(obj)
assert(cont_obj.flags['C_CONTIGUOUS'])
obj_data = cont_obj.data
data_b64 = base64.b64encode(obj_data)
return dict(__ndarray__=data_b64,
dtype=str(obj.dtype),
shape=obj.shape)
# Let the base class default method raise the TypeError
super(NumpyEncoder, self).default(obj)
def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
data = base64.b64decode(dct['__ndarray__'])
return np.frombuffer(data, dct['dtype']).reshape(dct['shape'])
return dct
expected = np.arange(100, dtype=np.float)
dumped = json.dumps(expected, cls=NumpyEncoder)
result = json.loads(dumped, object_hook=json_numpy_obj_hook)
# None of the following assertions will be broken.
assert result.dtype == expected.dtype, "Wrong Type"
assert result.shape == expected.shape, "Wrong Shape"
assert np.allclose(expected, result), "Wrong Values"发布于 2012-04-29 04:51:59
我在字典中找到了这个用于序列化一维numpy数组的json子类代码。我试过了,它对我很有效。
class NumpyAwareJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.ndarray) and obj.ndim == 1:
return obj.tolist()
return json.JSONEncoder.default(self, obj)我的字典是“results”。下面是我是如何写入“data.json”文件的:
j=json.dumps(results,cls=NumpyAwareJSONEncoder)
f=open("data.json","w")
f.write(j)
f.close()https://stackoverflow.com/questions/3488934
复制相似问题