问题描述
我想将多维Numpy数组转换为字符串,然后再将该字符串转换回等效的Numpy数组.
I would like to convert a multi-dimensional Numpy array into a string and, later, convert that string back into an equivalent Numpy array.
我不想将Numpy数组保存到文件中(例如,通过savetxt
和loadtxt
接口).
I do not want to save the Numpy array to a file (e.g. via the savetxt
and loadtxt
interface).
这可能吗?
推荐答案
您可以使用 np.tostring 和 np.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]])
请注意,tostring
返回的字符串不会保存dtype或原始数组的形状.您必须自己重新补充.
Note that the string returned by tostring
does not save the dtype nor the shape of the original array. You have to re-supply those yourself.
另一种选择是使用 np.save 或 np.savez 或 np.savez_compressed 写入io.BytesIO
对象(而不是文件) :
Another option is to use np.save or np.savez or np.savez_compressed to write to a io.BytesIO
object (instead of a file):
import numpy as np
import io
x = np.arange(12).reshape(3,4)
output = io.BytesIO()
np.savez(output, x=x)
字符串由
content = output.getvalue()
给定字符串,您可以使用np.load
将其加载回数组中:
And given the string, you can load it back into an array using np.load
:
data = np.load(io.BytesIO(content))
x = data['x']
此方法还存储dtype和形状.
This method stores the dtype and shape as well.
对于大型数组,np.savez_compressed
将为您提供最小的字符串.
For large arrays, np.savez_compressed
will give you the smallest string.
类似地,您可以使用 np.savetxt 和np.loadtxt
:
Similarly, you could use np.savetxt and np.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)
摘要:
Summary:
-
tostring
为您提供基础数据作为字符串,没有dtype或形状 -
save
与tostring
相似,除了它还保存dtype和形状(.npy格式) -
savez
以npz格式(未压缩)保存数组 -
savez_compressed
将数组保存为压缩的npz格式 -
savetxt
以易于阅读的格式格式化数组
tostring
gives you the underlying data as a string, with no dtype orshapesave
is liketostring
except it also saves dtype and shape (.npy format)savez
saves the array in npz format (uncompressed)savez_compressed
saves the array in compressed npz formatsavetxt
formats the array in a humanly readable format
这篇关于保存并从字符串检索Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!