我如何反序列化强制转换为字节串的numpy数组? [英] How can I unserialize a numpy array that was cast to a bytestring?
问题描述
我需要将一个numpy数组序列化为某些JSON兼容形式.由于我使用的框架无法让我访问JSON编码器/解码器对象,因此我一直坚持将numpy数组序列化为可以然后编组为JSON的对象.我选择了array.tobytes
或array.tostring
(两者似乎基本上是相同的).
I need to serialize a numpy array to some JSON-compatible form. Since the framework I'm using doesn't give me access to the JSON encoder/decoder object, I'm stuck serializing a numpy array to something that can then be marshalled into JSON. I've opted for either array.tobytes
or array.tostring
(both seem to be essentially the same thing).
下面是一个说明我的问题的示例:
Below is an example which illustrates my problem:
import numpy as np
a = np.random.rand(1024, 1024) # create array of random values
b = array.tobytes() # serialize array
a2 = np.fromstring(b)
当我检查a2
的值时,发现它只包含原始a
的第一行.换句话说,是a2 == a[0, :]
.
When I inspect the value of a2
, I find that it only contains the first line of the original a
. In other words, a2 == a[0, :]
.
如何解码整个阵列?
推荐答案
实际上numpy.fromstring()返回2维数组的1024X1024 intead的一维数组,您要做的就是将其重塑为1024X1024,
Actually numpy.fromstring() returns a single dimensional array of 1024X1024 intead of a 2 Dimensional array, All you need to do is reshape into 1024X1024,
尝试一下:-
import numpy as np
a = np.random.rand(1024, 1024) # create array of random values
b = array.tobytes()
np.fromstring(b).reshape(1024,1024)
这篇关于我如何反序列化强制转换为字节串的numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!