python - 在具有相同值的非零元素之间的numpy数组中填充零

标签 python arrays numpy vectorization

我有一个带有整数的一维 numpy numpy 数组,当且仅当下一个非零值相同时,我想用前一个非零值替换零。

例如,一个数组:

in: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1])
out: [1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1]

应该变成

out: [1,1,1,1,0,0,2,0,3,3,3,3,3,1,1,1]

有没有向量化的方法来做到这一点?我找到了一些方法来填充零值 here ,但不是如何处理异常,即不填充具有不同值的整数内的零。

最佳答案

这是一种矢量化方法,其灵感来自 NumPy based forward-filling对于此解决方案中的前向填充部分以及 maskingslicing -

def forward_fill_ifsame(x):
    # Get mask of non-zeros and then use it to forward-filled indices
    mask = x!=0
    idx = np.where(mask,np.arange(len(x)),0)
    np.maximum.accumulate(idx,axis=0, out=idx)

    # Now we need to work on the additional requirement of filling only
    # if the previous and next ones being same
    # Store a copy as we need to work and change input data
    x1 = x.copy()

    # Get non-zero elements
    xm = x1[mask]

    # Off the selected elements, we need to assign zeros to the previous places
    # that don't have their correspnding next ones different
    xm[:-1][xm[1:] != xm[:-1]] = 0

    # Assign the valid ones to x1. Invalid ones become zero.
    x1[mask] = xm

    # Use idx for indexing to do the forward filling
    out = x1[idx]

    # For the invalid ones, keep the previous masked elements
    out[mask] = x[mask]
    return out

样本运行-

In [289]: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1])

In [290]: np.vstack((x, forward_fill_ifsame(x)))
Out[290]: 
array([[1, 0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 3, 1, 0, 1],
       [1, 1, 1, 1, 0, 0, 2, 0, 3, 3, 3, 3, 3, 1, 1, 1]])

In [291]: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,1,1,0,1])

In [292]: np.vstack((x, forward_fill_ifsame(x)))
Out[292]: 
array([[1, 0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 0, 1],
       [1, 1, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 1, 1]])

In [293]: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,1,1,0,2])

In [294]: np.vstack((x, forward_fill_ifsame(x)))
Out[294]: 
array([[1, 0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 0, 2],
       [1, 1, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 0, 2]])

关于python - 在具有相同值的非零元素之间的numpy数组中填充零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48251448/

相关文章:

python - 如何在 Django 中扩展到 'base.html' 模板样式

c++ - 为什么我得到 “Invalid read of size 8”? (Valgrind)

ios - 单例函数 IOS

python - Pandas 分位数功能非常慢

python - 如何使用 numpy 对 Floyd-Steinberg 的抖动算法进行矢量化?

python - Gurobi 和 gurobipy - 使用 Python 日志记录时输出控制台加倍

python - django.db.migrations.exceptions.InconsistentMigrationHistory : Migration . ..在其依赖项之前应用

python - 如何检查列列表上的条件?

java - 从 String.split 创建数组时出现 NullPointerException

python-3.x - Numpy 具有复数和 +=