📜  numpy recarray.tostring()函数| Python(1)

📅  最后修改于: 2023-12-03 14:44:48.493000             🧑  作者: Mango

numpy recarray.tostring()函数 | Python

recarray.tostring()NumPy中的一个函数,可用于将记录数组(recarray)转换为表示数据的字符串,以便于传输或储存。

语法
recarray.tostring(order='C')
参数
  • order:字符串,可选参数,表示记录数组元素的顺序。默认为'C',即按行顺序存储。
返回值

该函数返回一个表示记录数组中所有元素的连续字符串。所生成的字符串可以用fromstring()函数重新转换为recarray(或其他NumPy数组类型)。

示例
import numpy as np

# 创建一个recarray
data = np.rec.array([(1,2.0,'Hello'),(2,3.0,'World')],
                    dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')])

# 转换为字符串
data_str = data.tostring()

print(data_str)

# 转换回recarray
data_re = np.fromstring(data_str, dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')])

print(data_re)

输出:

b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcd\xcc\x00\x40Hello\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x40\x40World\x00\x00\x00\x00\x00\x00\x00\x00'
[(1, 2., b'Hello') (2, 3., b'World')]

代码解释:

  1. 利用np.rec.array()创建一个记录数组data
  2. 使用tostring()函数将data转换为字符串类型data_str
  3. 使用fromstring()函数将data_str转换回原始的记录数组类型data_re
  4. 输出结果。

注意事项:

  1. 当使用不同的顺序(如'F')转换记录数组时,结果将取决于底层数组的顺序。