NumPy数组带有tobytes
方法,可为您转储其原始数据字节:
arr.tobytes()
您可以指定一个order
参数,以对多维数组使用C阶(行大写)或F阶(列大写)。
由于您要将字节转储到文件中,因此您可能还对tofile
方法感兴趣,该方法将字节直接转储到文件中:
arr.tofile(your_file)
tofile
始终使用C顺序。
如果需要更改字节序,可以使用byteswap
方法。 ({newbyteorder
具有更方便的签名,但不会更改基础字节,因此不会影响tobytes
。)
import sys
if sys.byteorder=='big':
arr = arr.byteswap()
data_bytes = arr.tobytes()
,
使用正确的dtype
,您可以将数组的数据缓冲区写入字节串或二进制文件:
In [449]: x = np.arange(4.,dtype='<f4')
In [450]: x
Out[450]: array([0.,1.,2.,3.],dtype=float32)
In [451]: txt = x.tostring()
In [452]: txt
Out[452]: b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@'
In [453]: x.tofile('test')
In [455]: np.fromfile('test','<f4')
Out[455]: array([0.,dtype=float32)
In [459]: with open('test','br') as f: print(f.read())
b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@'
更改结尾:
In [460]: x.astype('>f4').tostring()
Out[460]: b'\x00\x00\x00\x00?\x80\x00\x00@\x00\x00\x00@@\x00\x00'
,
您可以使用struct
来pack
像bytes
,
>>> import struct
>>> struct.pack('<f',3.14) # little-endian
b'\xc3\xf5H@'
>>> struct.pack('>f',3.14) # big-endian
b'@H\xf5\xc3'
,
save/savez
中有numpy
个方法:
将数据存储到磁盘,然后再次加载:
>>> np.save('/tmp/123',np.array([[1,2,3],[4,5,6]]))
>>> np.load('/tmp/123.npy')
array([[1,6]])
将压缩数据存储到磁盘,然后再次加载:
>>> a=np.array([[1,6]])
>>> b=np.array([1,2])
>>> np.savez('/tmp/123.npz',a=a,b=b)
>>> data = np.load('/tmp/123.npz')
>>> data['a']
array([[1,6]])
>>> data['b']
array([1,2])
>>> data.close()
本文链接:https://www.f2er.com/3119342.html