从字符串保存并检索Numpy数组

Ric*_*ard 4 python numpy

我想将多维Numpy数组转换为字符串,然后将该字符串转换回等效的Numpy数组.

我不想将Numpy数组保存到文件中(例如通过savetxtloadtxt接口).

这可能吗?

unu*_*tbu 13

你可以使用np.tostringnp.fromstring:

In [138]: x = np.arange(12).reshape(3,4)

In [139]: x.tostring()
Out[139]: '\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\x0b\x00\x00\x00'

In [140]: np.fromstring(x.tostring(), dtype=x.dtype).reshape(x.shape)
Out[140]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
Run Code Online (Sandbox Code Playgroud)

请注意,返回的字符串tostring不保存dtype,也不保存原始数组的形状.你必须自己重新供应这些.


另一种选择是使用np.savenp.saveznp.savez_compressed来写入io.BytesIO对象(而不是文件):

import numpy as np
import io

x = np.arange(12).reshape(3,4)
output = io.BytesIO()
np.savez(output, x=x)
Run Code Online (Sandbox Code Playgroud)

字符串由.给出

content = output.getvalue()
Run Code Online (Sandbox Code Playgroud)

给定字符串,您可以使用np.load以下命令将其加载回数组:

data = np.load(io.BytesIO(content))
x = data['x']
Run Code Online (Sandbox Code Playgroud)

此方法也存储dtype和形状.

对于大型数组,np.savez_compressed将为您提供最小的字符串.


同样,您可以使用np.savetxtnp.loadtxt:

import numpy as np
import io

x = np.arange(12).reshape(3,4)
output = io.BytesIO()
np.savetxt(output, x)
content = output.getvalue()
# '0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00\n4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00 7.000000000000000000e+00\n8.000000000000000000e+00 9.000000000000000000e+00 1.000000000000000000e+01 1.100000000000000000e+01\n'

x = np.loadtxt(io.BytesIO(content))
print(x)
Run Code Online (Sandbox Code Playgroud)

摘要:

  • tostring 以字符串形式提供基础数据,没有dtype或形状
  • save就像tostring它除了它还保存dtype和形状(.npy格式)
  • savez 以npz格式保存数组(未压缩)
  • savez_compressed 以压缩的npz格式保存数组
  • savetxt 以人类可读的格式格式化数组