【问题标题】:How to fill specific array values which indexes are equally distant from before and next non zero values indexes?如何填充索引与之前和下一个非零值索引等距的特定数组值?
【发布时间】:2019-04-25 15:00:42
【问题描述】:

我试图仅更改索引(+-1)位于其他非零值索引之间的数组的零值。

Input:
a = pandas.Series(np.array[0,0,-2,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,-1,0])

Desired output:
[0,0,-2,0,0,0,999,0,0,0,5,0,0,0,999,0,0,0,-1,0]

我使用 for 循环以非常低效的方式解决了这个问题,需要永远完成

我的目标是用 numpy.where 来做,但我不知道管理索引

margen = 1
extra_forc = 100
for i in range(extra_forc, len(a)-extra_forc):
    if a.values[i] != 0: continue
    past = np.nonzero(a.values[i-extra_forc:i][::-1])[0]
    fut = np.nonzero(a.values[i+1:i+1+extra_forc])[0]
    if len(past) > 0 and len(fut) > 0:
        if abs(np.amin(past) - np.amin(fut)) <= margen:
            a.values[i] = 999

这就是我现在尝试但没有成功:

a = np.where((abs(np.amin(np.nonzero([a.shift(-i) for i in range(extra_forc)])[0], axis=0) - np.amin(np.nonzero([a.shift(i) for i in range(extra_forc)][::-1])[0], axis=0)) < margen), 999, a)

【问题讨论】:

    标签: python pandas numpy indexing


    【解决方案1】:

    受到启发并找到了更好的解决方案。可能不是最好的,但效果很好。

    non_cero_idxs = np.nonzero(a)[0]
    ceros_idxs = np.convolve(non_cero_idxs, [0.5, 0.5], mode='same').astype(dtype=np.int32)
    a.loc[ceros_idxs[1:]] = 999
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 2018-07-28
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2019-05-04
      相关资源
      最近更新 更多