首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从文件中读取二进制数据

从文件中读取二进制数据
EN

Code Review用户
提问于 2015-03-31 14:28:07
回答 1查看 170关注 0票数 0

我有一个具有交替的uint8和uint64数据标记的二进制文件。我用下面的一行读到了这些内容:

代码语言:javascript
运行
复制
clicks = np.fromfile(filename, dtype=[('time','u8'),('channel','u2')])

这工作得很好,而且足够快。现在,我想遍历数组,并将时间值设置为与通道7上看到的最后一次“单击”(所谓的“门”单击)有关的时间差。数组按时间排序。在C语言中,我会使用一个简单的for循环来完成这个任务(这非常快)。当我在python中实现这个时,数据速率只有2MB/S。

代码语言:javascript
运行
复制
    ''' 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的数据速率。

EN

回答 1

Code Review用户

发布于 2015-04-03 09:41:52

您可以使用numpy.digitize对数据进行分组并对循环进行矢量化。演示:

代码语言:javascript
运行
复制
>>> 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)
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/85507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档