来自字节或字符串的 Numpy recarray

Numpy recarray from bytes or string

我有一个过程需要将 numpy recarray 转换为字节, 然后从字节重建 recarray。

但是,我不确定如何从字节恢复数组。

有人知道我该怎么做吗?

示例代码:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.zeros(500))
rec = df.to_records()
rec_s = rec.tostring()  # this returns a bytes object

# perform some computation

new_rec = <method to recover from bytes>(rec_s)

注意:我实际上不需要使用 numpy recarry,只需要一些结构可以让我将 pandas 数据帧转换为字节对象,并恢复它。

In [497]: arr = np.ones(3, dtype='i,i,f')                                                      
In [498]: arr                                                                                  
Out[498]: 
array([(1, 1, 1.), (1, 1, 1.), (1, 1, 1.)],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<f4')])
In [499]: astr = arr.tostring()                                                                
In [500]: astr                                                                                 
Out[500]: b'\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x80?\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x80?\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x80?'

使用相同的数据类型恢复它:

In [502]: np.frombuffer(astr, arr.dtype)                                                       
Out[502]: 
array([(1, 1, 1.), (1, 1, 1.), (1, 1, 1.)],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<f4')])

如果源是二维的,你也必须重新整形