我有一个二进制文件,其中包含交错的数据;下面是一个Python脚本,它将生成一个示例:
test-np-array-il-split-01.py
:
#!/usr/bin/env python2
# (also works with python3)
# generate a test binary file with interleaved floats
thebinfilename = "il3ch.binfile"
import struct
# https://docs.python.org/2/library/struct.html : "=" native; "<" little-endian; ">" big-endian
with open(thebinfilename, 'wb') as f:
for ix in range(10):
decremain = ix/100.0;
for ic in range(3):
thischannum = ic+1 + decremain;
print(thischannum)
f.write(struct.pack("=f", thischannum))
基本上,只要运行python test-np-array-il-split-01.py
,就会在同一个目录中得到一个二进制文件il3ch.binfile
。此文件基本上具有以下浮点数序列:
1.0, 2.0, 3.0, 1.01, 2.01, 3.01, 1.02, 2.02, 3.02, 1.03, 2.03, 3.03, 1.04, 2.04, 3.04, 1.05, 2.05, 3.05, 1.06, 2.06, 3.06, 1.07, 2.07, 3.07, 1.08, 2.08, 3.08, 1.09, 2.09, 3.09
。。。以二进制浮点形式存储。你知道吗
基本上,我想获得单独的通道数据作为单独的numpy数组,其中通道将是:
因此,我尝试编写以下脚本(将其放在与test-np-array-il-split-01.py
和il3ch.binfile
相同的文件夹中):
test-np-array-il-split-02.py
:
#!/usr/bin/env python2
# (also works with python3)
# read a test binary file with interleaved floats
thebinfilename = "il3ch.binfile"
import numpy as np
dt = np.dtype( [ ('CH1', '<f4'), ('CH2', '<f4'), ('CH3', '<f4') ] )
bin_np_arr = np.fromfile(thebinfilename, dtype=dt)
print(bin_np_arr.shape) # (10,)
print(bin_np_arr)
# [(1. , 2. , 3. ) (1.01, 2.01, 3.01) (1.02, 2.02, 3.02)
# (1.03, 2.03, 3.03) (1.04, 2.04, 3.04) (1.05, 2.05, 3.05)
# (1.06, 2.06, 3.06) (1.07, 2.07, 3.07) (1.08, 2.08, 3.08)
# (1.09, 2.09, 3.09)]
ch1, ch2, ch3 = bin_np_arr[:][0], bin_np_arr[:][1], bin_np_arr[:][2]
print(ch1) # (1., 2., 3.) # -> however, I want 1.0, 1.01, 1.02, 1.03 ... etc here!
所以,好的方面是,通过使用np.dtype
规范,我可以在数据中强加一种结构—但是,作为输出np.数组(CH1,CH2,CH3)元组,我真的不知道我需要做什么,来拆分这个np.数组. 你知道吗
所以我的问题是:如何分割bin_np_arr
np.数组分成三部分np.阵列,这将对应于单个通道数据?另外,我是否应该以不同于文件的方式读入bin_np_arr
(例如,它有一个不同的.shape
),这样它更适合这种“每通道”分割?你知道吗
使用structured array时,可以使用
['<field name>']
语法访问与每个字段对应的数组。在您的情况下,您可以简单地执行以下操作:相关问题 更多 >
编程相关推荐