Numpy入门[9]——数组与字符串的转换
参考:
https://ailearning.apachecn.org/
使用Jupyter进行练习
import numpy as np
tobytes方法
tostring()
已被弃用。使用tobytes()
代替。
a = np.array([[1,2],
[3,4]],
dtype = np.uint8)
转化为字符串:
a.tobytes()
b'\x01\x02\x03\x04'
可以使用不同的顺序来转换字符串:
a.tobytes(order='F')
b'\x01\x03\x02\x04'
这里使用了Fortran的格式,按照列来读数据。
frombuffer函数
fromstring()
方法已经被弃用,使用 frombuffer()
替代
可以使用 frombuffer 函数从字符串中读出数据,不过要指定类型:
s = a.tobytes()
b = np.frombuffer(s, dtype=np.uint8)
b
array([1, 2, 3, 4], dtype=uint8)
此时,返回的数组是一维的,需要重新设定维度:
b.shape = 2,2
b
array([[1, 2],
[3, 4]], dtype=uint8)