python - 在 numpy 数组中查找相同值序列的长度(运行长度编码)

标签 python matlab numpy matplotlib

在一个 pylab 程序(也可能是一个 matlab 程序)中,我有一个代表距离的 numpy 数组:d[t]是时间t距离 (我的数据的时间跨度是 len(d) 时间单位)。

我感兴趣的事件是距离低于某个阈值时,我想计算这些事件的持续时间。使用 b = d<threshold 很容易得到一个 bool 数组。 ,问题归结为计算 b 中 True-only 单词的长度序列。 .但我不知道如何有效地做到这一点(即使用 numpy 原语),我求助于遍历数组并进行手动更改检测(即当值从 False 变为 True 时初始化计数器,只要值为 True 就增加计数器,并在值返回 False 时将计数器输出到序列)。但这非常慢。

如何有效地检测 numpy 数组中的那种序列?

下面是一些说明我的问题的python代码:第四个点需要很长时间才能出现(如果没有,请增加数组的大小)

from pylab import *

threshold = 7

print '.'
d = 10*rand(10000000)

print '.'

b = d<threshold

print '.'

durations=[]
for i in xrange(len(b)):
    if b[i] and (i==0 or not b[i-1]):
        counter=1
    if  i>0 and b[i-1] and b[i]:
        counter+=1
    if (b[i-1] and not b[i]) or i==len(b)-1:
        durations.append(counter)

print '.'

最佳答案

适用于任何数组的完全 numpy 矢量化和通用 RLE(也适用于字符串、 bool 值等)。

输出运行长度、起始位置和值的元组。

import numpy as np

def rle(inarray):
        """ run length encoding. Partial credit to R rle function. 
            Multi datatype arrays catered for including non Numpy
            returns: tuple (runlengths, startpositions, values) """
        ia = np.asarray(inarray)                # force numpy
        n = len(ia)
        if n == 0: 
            return (None, None, None)
        else:
            y = ia[1:] != ia[:-1]               # pairwise unequal (string safe)
            i = np.append(np.where(y), n - 1)   # must include last element posi
            z = np.diff(np.append(-1, i))       # run lengths
            p = np.cumsum(np.append(0, z))[:-1] # positions
            return(z, p, ia[i])

相当快(i7):

xx = np.random.randint(0, 5, 1000000)
%timeit yy = rle(xx)
100 loops, best of 3: 18.6 ms per loop

多种数据类型:

rle([True, True, True, False, True, False, False])
Out[8]: 
(array([3, 1, 1, 2]),
 array([0, 3, 4, 5]),
 array([ True, False,  True, False], dtype=bool))

rle(np.array([5, 4, 4, 4, 4, 0, 0]))
Out[9]: (array([1, 4, 2]), array([0, 1, 5]), array([5, 4, 0]))

rle(["hello", "hello", "my", "friend", "okay", "okay", "bye"])
Out[10]: 
(array([2, 1, 1, 2, 1]),
 array([0, 2, 3, 4, 6]),
 array(['hello', 'my', 'friend', 'okay', 'bye'], 
       dtype='|S6'))

与上述 Alex Martelli 的结果相同:

xx = np.random.randint(0, 2, 20)

xx
Out[60]: array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1])

am = runs_of_ones_array(xx)

tb = rle(xx)

am
Out[63]: array([4, 5, 2, 5])

tb[0][tb[2] == 1]
Out[64]: array([4, 5, 2, 5])

%timeit runs_of_ones_array(xx)
10000 loops, best of 3: 28.5 µs per loop

%timeit rle(xx)
10000 loops, best of 3: 38.2 µs per loop

比 Alex 稍慢(但仍然非常快),而且更灵活。

关于python - 在 numpy 数组中查找相同值序列的长度(运行长度编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1066758/

相关文章:

Python - 考虑到官方定义 Numpy 应该是一个模块

python - map 字典查找

python - 如何处理 python 参数中的引号

python - 从 Matlab 到 Python - 求解函数

Matlab-将每隔一列替换为另一个向量

python - 查找并替换 numpy ndarray 中的特定值?

Python/Json :Expecting property name enclosed in double quotes

python - 优化Django模型保存方法获取上传文件路径

matlab - 如何在matlab中找到均方误差

python - 解析 numpy 数组的字符串表示