我以以下格式将混合数据存储在字节数组中
[ np.int64(1) np.int64(2) np.int64(3) np.float32(1.0) np.float32(2.0) np.float32(3.0) np.float64(1) np.float64(2) np.float64(3) ]
我知道每个新类型的偏移量,但我不确定如何从中创建numpy数组。通常您可以使用结构化数组,但是考虑到数据的格式,我不确定如何做到这一点。如有任何帮助,不胜感激。
数组是9个值(3 int64, 3 float32, 3 float64),目前还没有在结构化数组中使用它。它只是一个来自其他位置的字节数组。把3想象成一个数字,如果我有10个int64,我将有10个float32和10个float64。这类似于3个串联数组,其中每个数组的类型不同,但所有数组的大小相同。
例如:输入(字节数组)
中bytearray (b x00 x00 x00 x00 x00 x00 x00 x01 x00 x00 x00 x00 x00 x00 x00 x02 x00 x00 x00 x00 x00 x00 x00 x03吗? x80 x00 x00@ x00 x00 x00@@ x00 x00@ x18 x00 x00 x00 x00 x00 x00@ x1c x00 x00 x00 x00 x00 x00@ x00 x00 x00 x00 x00 x00")
output (numpy array)
我想把它放入一个混合类型的numpy数组(没有复制)
[1 2 3 1.0 2.0 3.0 1.0 2.0 3.0]
这是使用
生成的np.array ([1, 2, 3, np.float32 (1) np.float32 (2), np.float32 (3), np.float64 (1) np.float64 (2), np.float64 (3)], dtype = '对象')
构造一个字节数组,我认为看起来像你有什么(但这是猜测的东西):
In [347]: x,y,z = np.arange(3, dtype='int64'), np.arange(1,4,dtype='float32'),np.arange(2,5,dtype='int32')
In [349]: barr = x.tobytes()+y.tobytes()+z.tobytes()
In [350]: barr
Out[350]: b'x00x00x00x00x00x00x00x00x01x00x00x00x00x00x00x00x02x00x00x00x00x00x00x00x00x00x80?x00x00x00@x00x00@@x02x00x00x00x03x00x00x00x04x00x00x00'
创建使用barr
和不同偏移量的数组:
In [352]: x1 = np.ndarray(3,'int64',barr,0)
In [353]: x1
Out[353]: array([0, 1, 2], dtype=int64)
In [354]: y1 = np.ndarray(3,'float32',barr,offset=3*8)
In [355]: y1
Out[355]: array([1., 2., 3.], dtype=float32)
In [356]: z1 = np.ndarray(3,'int32',barr,offset=3*8+3*4)
In [357]: z1
Out[357]: array([2, 3, 4])
扁平结构数组
定义复合dtype -根据需要使用字符串重复:
In [362]: dt = np.dtype('i8,i8,i8,f4,f4,f4,i4,i4,i4')
In [363]: dt
Out[363]: dtype([('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<f4'), ('f4', '<f4'), ('f5', '<f4'), ('f6', '<i4'), ('f7', '<i4'), ('f8', '<i4')])
In [364]: xyz = np.ndarray(1,dt,barr)
In [365]: xyz
Out[365]:
array([(0, 1, 2, 1., 2., 3., 2, 3, 4)],
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<f4'), ('f4', '<f4'), ('f5', '<f4'), ('f6', '<i4'), ('f7', '<i4'), ('f8', '<i4')])
In [366]: xyz['f4']
Out[366]: array([2.], dtype=float32)
但是跨领域做"数学"很难。
使用注释的dtype:n=3; dt1 = np.dtype('>i8,'*n + '>f4,'*n + '>i4,'*n)
更好dtype
In [367]: dt = np.dtype([('x','i8',3),('y','f4',3),('z','i4',3)])
In [368]: dt
Out[368]: dtype([('x', '<i8', (3,)), ('y', '<f4', (3,)), ('z', '<i4', (3,))])
In [369]: xyz = np.ndarray(1,dt,barr)
In [370]: xyz
Out[370]:
array([([0, 1, 2], [1., 2., 3.], [2, 3, 4])],
dtype=[('x', '<i8', (3,)), ('y', '<f4', (3,)), ('z', '<i4', (3,))])
In [371]: xyz['y']
Out[371]: array([[1., 2., 3.]], dtype=float32)
只有3个字段,这在字符上更接近我的第一个解决方案。