【问题标题】:applying RLE on numpy 2d array在 numpy 二维数组上应用 RLE
【发布时间】:2017-05-21 12:15:14
【问题描述】:

我有一个像这样的 numpy 二维数组:

np.array([[1,1,1,0], [1,0,0,1]])

如何有效地在这个二维数组上应用 RLE?我的数据集的形状是 (4000, 3000)

我可以在不使用 numpy 的情况下使用这种逻辑对字符串进行 rle。

    for i in new_bin_data:
        if i == '0':
            if prev != i:
                final_result.append(count)
                count = 0
                prev = '0'
            count += 1
        else:
            if prev != i:
                final_result.append(count)
                count = 0
            count += 1
            prev = '1'

【问题讨论】:

  • prev和其他人不是初始化了吗?
  • 是的,他们是。但我只是将我的代码用于我所遵循的逻辑。这是一个字符串的工作程序

标签: python arrays numpy run-length-encoding


【解决方案1】:

不确定您在寻找什么。 下面是一些计算行的 RLE 编码的代码。

def rle(inarray):
    """
    From: https://stackoverflow.com/questions/1066758/find-length-of-sequences-of-identical-values-in-a-numpy-array-run-length-encodi

    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])



def rle_2d(a, unused_value):
    """
    compute rle encoding of each row in the input array

    Args:
        a: 2d numpy array
        unused_value: a value that does not appear in the input array a

    Returns:
        list of (length, positions, values) tuples. The length of the list is the number of rows in
        the input matrix

    """
    r, c = a.shape          # rows, columns
    a = np.hstack([a, np.ones((r, 1), dtype=a.dtype) * unused_value])
    a = a.reshape(-1)
    l, p, v = rle(a)        # length,  positions, values
    y = p // (c + 1)
    x = p % (c + 1)

    rl, rp, rv = rle(y)
    result = []
    for i in range(r):
        assert(rv[i] == i)
        li = l[rp[i]: rp[i] + rl[i] - 1]
        pi = x[rp[i]: rp[i] + rl[i] - 1]
        vi = v[rp[i]: rp[i] + rl[i] - 1]
        result.append((li, pi, vi))
    return result

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多