繁体   English   中英

修改numpy数组以获得元素之间的最小值

[英]Modifying numpy array to get minimum number of values between elements

我有一个numpy数组形式: arr = 0 0 0 1 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1

我想修改它,使得任何两个1之间至少有7个0。 如果少于七个0,那么将intervining 1转换为0.我认为numpy.where可以在这里工作,但不知道如何以succint,pythonic方式执行:

输出应如下所示:

0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

numpy.where(arr[:] > 1.0, 1.0, 0.0)

以下代码是一个非常丑陋的黑客,但它可以在线性时间内完成工作(假设7是固定的),而不需要使用Python循环而不需要像Numba或Cython这样的东西。 我建议不要使用它,特别是下个月7可能是700。

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr2 = numpy.append(1-arr, [0]*7)
numpy.power.at(rolling_window(arr2[1:], 7), np.arange(len(arr)), arr2[:-7, None])
arr = 1 - arr2[:-7]

它的工作原理是将1s设置为0,反之亦然,然后对于每个元素x ,将接下来的7个点中的每个元素y设置为y**x ,然后撤消0/1开关。 电源操作将所有内容设置在0到1的7个空间内,使得效果立即可见于阵列下方的电源操作。

现在这只是一个使用for循环和ifs的简单实现,但我很确定它可以被压缩。(很多!)是的,没有必要为此做Numpy,它只会让你复杂化。

question = [0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1]
result = [0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
indexesOf1s = []
for index,item in enumerate(question):     #Here just calculate all the index of 1s
if item == 1:
    indexesOf1s.append(index)
for i in indexesOf1s:               #Iterate over the indexes and change acc to conditions
    sub = i - indexes[indexes.index(i)-1]
    if sub>0 and sub>=7:
        question[i] = 1
    elif sub>0:
        question[i] = 0
print question 
print result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM