在實際工作中有個需求是需要將 Numpy
的二進制對象轉換爲字符串,經過某種處理之後,再將字符串還原爲 Numpy
對象,這就需要用到 Numpy
自帶的 tostring
和 fromstring
方法。在此記錄下其使用方法。
1. tostring
方法
將 numpy
對象轉換爲字符串:
In [1]: import numpy as np
In [2]: a = np.array([[1,2], [3,4]])
In [3]: a
Out[3]:
array([[1, 2],
[3, 4]])
In [4]: b = a.tostring()
In [5]: b
Out[5]: b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'
In [6]:
2. fromstring
方法
fromstring
或者 frombuffer
可以將字符串對象轉換爲對應的 numpy
對象。
In [7]: a.dtype
Out[7]: dtype('int32')
In [8]: c = np.fromstring(b, dtype=np.int32)
g:\python\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
"""Entry point for launching an IPython kernel."""
In [9]: c = np.frombuffer(b, dtype=np.int32)
In [10]: c
Out[10]: array([1, 2, 3, 4])
In [11]: c.shape=(2,2)
In [12]: c
Out[12]:
array([[1, 2],
[3, 4]])
In [13]:
注意:Python3 中更推薦使用 frombuffer
來將字符串轉換爲二進制,並且要設置轉換的 dtype
類型,否則默認按照一維進行轉換。
3. 文本文件處理
對於文本文件,推薦使用
loadtxt
genfromtxt
savetxt
4. 二進制文件處理
對於二進制文本文件,推薦使用
save
load
savez