挑战在于不仅要保存数据缓冲区,还要保存shape和dtype。
np.fromstring读取数据缓冲区,但作为一维数组;您必须从其他位置获取dtype和形状。
In [184]: a=np.arange(12).reshape(3,4)In [185]: np.fromstring(a.tostring(),int)Out[185]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])In [186]: np.fromstring(a.tostring(),a.dtype).reshape(a.shape)Out[186]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
保存Python对象的一种受人尊敬的机制是
pickle,并且与
numpypickle兼容:
In [169]: import pickleIn [170]: a=np.arange(12).reshape(3,4)In [171]: s=pickle.dumps(a*2)In [172]: sOut[172]: "cnumpy.core.multiarrayn_reconstructnp0n(cnumpynndarraynp1n(I0ntp2nS'b'np3ntp4nRp5n(I1n(I3nI4ntp6ncnumpyndtypenp7n(S'i4'np8nI0nI1ntp9nRp10n(I3nS'<'np11nNNNI-1nI-1nI0ntp12nbI00nS'\x00\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00\x06\x00\x00\x00\x08\x00\x00\x00\n\x00\x00\x00\x0c\x00\x00\x00\x0e\x00\x00\x00\x10\x00\x00\x00\x12\x00\x00\x00\x14\x00\x00\x00\x16\x00\x00\x00'np13ntp14nb."In [173]: pickle.loads(s)Out[173]: array([[ 0, 2, 4, 6], [ 8, 10, 12, 14], [16, 18, 20, 22]])
有一个numpy函数可以读取泡菜字符串:
In [181]: np.loads(s)Out[181]: array([[ 0, 2, 4, 6], [ 8, 10, 12, 14], [16, 18, 20, 22]])
您提到
np.save了一个字符串,但不能使用
np.load。一种解决方法是进一步进入代码并使用
np.lib.npyio.format。
In [174]: import StringIOIn [175]: S=StringIO.StringIO() # a file like string bufferIn [176]: np.lib.npyio.format.write_array(S,a*3.3)In [177]: S.seek(0) # rewind the stringIn [178]: np.lib.npyio.format.read_array(S)Out[178]: array([[ 0. , 3.3, 6.6, 9.9], [ 13.2, 16.5, 19.8, 23.1], [ 26.4, 29.7, 33. , 36.3]])
该
save字符串的标头带有
dtype和
shape信息:
In [179]: S.seek(0)In [180]: S.readlines()Out[180]: ["x93NUMPYx01x00Fx00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 4), } n", 'x00x00x00x00x00x00x00x00ffffffn', '@ffffffx1a@xccxccxccxccxccxcc#@ffffff*@x00x00x00x00x00x800@xccxccxccxccxccxcc3@x99x99x99x99x99x197@ffffff:@33333xb3=@x00x00x00x00x00x80@@fffff&B@']如果您想要一个人类可读的字符串,则可以尝试
json。
In [196]: import jsonIn [197]: js=json.dumps(a.tolist())In [198]: jsOut[198]: '[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]'In [199]: np.array(json.loads(js))Out[199]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
进入/离开数组的列表表示形式是最明显的用途
json。有人可能会写出更详尽
json的数组表示形式。
您也可以选择
csv格式化路线-有关读取/写入csv数组的问题很多。
'[[ 0.5544 0.4456], [ 0.8811 0.1189]]'
是用于此目的的较差的字符串表示形式。它看起来确实很像
str()数组的,但是使用
,代替
n。但是,没有一种解析嵌套的干净方法,
[]缺少分隔符是很痛苦的。如果持续使用,
,则
json可以将其转换为列表。
np.matrix接受类似MATLAB的字符串:
In [207]: np.matrix(' 0.5544, 0.4456;0.8811, 0.1189')Out[207]: matrix([[ 0.5544, 0.4456], [ 0.8811, 0.1189]])In [208]: str(np.matrix(' 0.5544, 0.4456;0.8811, 0.1189'))Out[208]: '[[ 0.5544 0.4456]n [ 0.8811 0.1189]]'


