【问题标题】:Filling zeros in numpy array that are between non-zero elements with the same value在具有相同值的非零元素之间填充numpy数组中的零
【发布时间】:2018-06-23 09:39:53
【问题描述】:

我有一个带有整数的一维 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,但没有找到例外情况的方法,即不填充具有不同值的整数中的零。

【问题讨论】:

  • 异常是什么意思?你有非数字值吗?
  • 我的意思是 iff 语句,不填充具有不同值的整数内的零。
  • 啊哈,好吧,我在程序异常方面阅读了“例外”,而不是规则的例外。对不起。
  • @BramZijlstra 是否总是在 same 元素之间只有一个零,即[1, 0, 1..., 3, 0, 3, ..., 1,0,1]
  • 不,可以出现多个零。

标签: python arrays numpy vectorization


【解决方案1】:

这是一种矢量化方法,该方法从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]])

【讨论】:

  • @Divakar 当我研究 张量分解 时,其中一项任务是分析人们常用来超链接页面的术语。它是在真实数据集上完成的。分析结果并不是那么好。因为,人们几乎总是使用“看这里”、“在这篇文章中”、“另一个博客”、“在这个链接上”等词,这些词并不那么有趣;因此,在超链接时,最好使用问题主题。即。 “前向填充 NaN 值的最有效方法” 这应该使链接标题信息丰富:) 并且更好一点
  • @Divakar,你总是以你理解看似复杂的需求并找到直截了当、可能是最有效的解决方案的能力激励我
猜你喜欢
  • 2015-08-09
  • 1970-01-01
  • 2023-01-31
  • 2016-11-06
  • 1970-01-01
  • 2018-10-05
  • 2017-10-24
  • 1970-01-01
  • 2015-11-09
相关资源
最近更新 更多