代码之家  ›  专栏  ›  技术社区  ›  Joe

列表窗口中的最大百分位数为99

  •  1
  • Joe  · 技术社区  · 6 年前

    我有一个列表列表(2000x1000),但以这个列表(10x3)为例:

    l = [[8, 7, 6], [5, 3, 1], [4, 5, 9], [1, 5, 1], [3, 5, 7], [8, 2, 5], [1, 9, 2], [8, 7, 6], [9, 9, 9], [4, 5, 9]] 
    

    在此示例中,每个列表对应于每个瞬间的3个测量值:

    t0 -&燃气轮机[8,7,6]

    t1 等等。

    我想比较4个瞬间的位置窗口的测量值,取最大值,即峰峰值的99%。

    让我们考虑第一个窗口:

    [8, 7, 6], [5, 3, 1], [4, 5, 9], [1, 5, 1] :
    [8,5,4,1] -> peak to peak: 8-1=7
    [7,3,5,5] -> ptp=4
    [6,1,9,1] -> ptp=8
    

    [7,4,8] 我想取99%的最大值,在这种情况下 7

    对于第二个窗口:

    [5, 3, 1], [4, 5, 9], [1, 5, 1], [3, 5, 7]:
    [5,4,1,3] -> ptp=4
    [3,5,5,5] -> ptp=2
    [1,9,1,7] -> ptp=8
    

    4 对所有大小为4的窗口执行此操作后,我想用这些值创建一个列表。

    我的代码是下面的,但是速度很慢。有没有一个快速的方法来实现这一点?

    注意:我不能使用pandas,Numpy版本应该是<=1.6

    num_meas = 4
    m = []
    for index, i in enumerate(l):
        if index < len(l) - num_meas + 1:
            p = []
            for j in range(len(i)):
                t = []
                for k in range(num_meas):
                    t.append(l[index + k][j])
                t = [x for x in t if ~np.isnan(x)]
                try:
                    a = np.ptp(t)
                except ValueError:
                    a = 0
                p.append(a)
            perce = np.percentile(p, 99)
            p = max([el for el in p if el < perce])
            m.append(p)
    print m
    

    输出:

    [7, 4, 7, 6, 5, 7, 7]
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Niko Z.    6 年前

    请检查以下代码是否适用于NumPy 1.6:

    import numpy as np
    
    l = [[8, 7, 6], [5, 3, 1], [4, 5, 9], [1, 5, 1], [3, 5, 7], [8, 2, 5],
         [1, 9, 2], [8, 7, 6], [9, 9, 9], [4, 5, 9]]
    
    l = np.array(l)
    
    # range matrix
    mat_ptp = np.zeros((l.shape[0]-3, l.shape[1]))
    
    for i in range(l.shape[0]-3):
        l[i:i+4].ptp(axis=0, out=mat_ptp[i])
    
    percentiles = np.percentile(mat_ptp, 99, axis=1)
    greater_pos = np.greater_equal(mat_ptp, percentiles.reshape(-1, 1))
    mat_ptp[greater_pos] = -np.inf
    
    result = np.max(mat_ptp, axis=1)
    

    for 循环和 append 功能。

    编辑

    为了验证有关性能的问题,以下是结果:

    l = np.random.randint(0, 100, size=(200, 100))
    

    timeit :

    OP code: 0.5197743272900698 ms in average
    Code above: 0.0021439407201251015 in average