我有一个具有交替的uint8和uint64数据标记的二进制文件。我用下面的一行读到了这些内容:
clicks = np.fromfile(filename, dtype=[('time','u8'),('channel','u2')])这工作得很好,而且足够快。现在,我想遍历数组,并将时间值设置为与通道7上看到的最后一次“单击”(所谓的“门”单击)有关的时间差。数组按时间排序。在C语言中,我会使用一个简单的for循环来完成这个任务(这非常快)。当我在python中实现这个时,数据速率只有2MB/S。
''' create an array with the indices of the channel-7 clicks '''
gate_clicks = clicks['channel']==7
gate_ind = np.array(range(len(gate_clicks)))
gate_ind = gate_ind[gate_clicks]
gate_ind_shift = np.delete(gate_ind,0,0)
''' slice out the clicks between to gate clicks and set the time stamps '''
for start,end in zip(gate_ind,gate_ind_shift):
start_time = data[start]['time']
slice = data[start:end]
slice['time'] = slice['time']-start_time
data[start:end] = slice这给出了大约4的数据速率。
发布于 2015-04-03 09:41:52
您可以使用numpy.digitize对数据进行分组并对循环进行矢量化。演示:
>>> clicks
array([(0L, 7), (1L, 0), (2L, 0), (3L, 0), (4L, 7), (5L, 0), (6L, 0),
(7L, 0), (8L, 0), (9L, 7)],
dtype=[('time', '<u8'), ('channel', '<u2')])
>>> bins = clicks['time'][clicks['channel']==7]
>>> bins
array([0, 4, 9], dtype=uint64)
>>> ind = np.digitize(clicks['time'], bins) - 1
>>> ind
array([0, 0, 0, 0, 1, 1, 1, 1, 1, 2])
>>> bins[ind]
array([0, 0, 0, 0, 4, 4, 4, 4, 4, 9], dtype=uint64)
>>> clicks['time'] - bins[ind]
array([0, 1, 2, 3, 0, 1, 2, 3, 4, 0], dtype=uint64)https://codereview.stackexchange.com/questions/85507
复制相似问题