[英]Numpy recarray from bytes or string
I have a process where I need to convert a numpy recarray to bytes, and after that reconstruct the recarray from the bytes.我有一个过程,我需要将 numpy recarray 转换为字节,然后从字节重建 recarray。
However, I am not sure how to do recover the array from bytes.但是,我不确定如何从字节中恢复数组。
Does anyone know how could I do it?有谁知道我该怎么做?
Example code:示例代码:
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)
Note: I don't actually need to use numpy recarry, just some structure that will allow me to transform the pandas dataframe into a bytes object, and also recover it.注意:我实际上并不需要使用 numpy rearry,只需要使用一些结构来允许我将 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?'
Recover it using the same dtype:使用相同的 dtype 恢复它:
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')])
If the source was 2d, you'd have to reshape as well如果源是 2d,你也必须重塑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.