简体   繁体   English

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

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

I have a numpy array of the form: 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 我有一个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

I would like to modify it such that there are atleast seven 0s between any two 1s. 我想修改它,使得任何两个1之间至少有7个0。 If there are less than seven 0s, then convert the intervining 1's to 0. I am thinking that numpy.where could work here, but not sure how to do it in a succint, pythonic manner: 如果少于七个0,那么将intervining 1转换为0.我认为numpy.where可以在这里工作,但不知道如何以succint,pythonic方式执行:

The output should look like this: 输出应如下所示:

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)

The following code is a really ugly hack, but it gets the job done in linear time (assuming 7 is fixed) without resorting to Python loops and without needing anything like Numba or Cython. 以下代码是一个非常丑陋的黑客,但它可以在线性时间内完成工作(假设7是固定的),而不需要使用Python循环而不需要像Numba或Cython这样的东西。 I don't recommend using it, especially if 7 might be 700 next month. 我建议不要使用它,特别是下个月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]

It works by setting 1s to 0s and vice versa, then for each element x , setting each element y in the next 7 spots to y**x , then undoing the 0/1 switch. 它的工作原理是将1s设置为0,反之亦然,然后对于每个元素x ,将接下来的7个点中的每个元素y设置为y**x ,然后撤消0/1开关。 The power operation sets everything within 7 spaces of a 0 to 1, in such a way that the effect is immediately visible to power operations further down the array. 电源操作将所有内容设置在0到1的7个空间内,使得效果立即可见于阵列下方的电源操作。

Now this is just a simple implementation using for loops and ifs but I am pretty sure it can be condensed.(a lot!) And yeah there's no need to do Numpy for this, it will only complicate things for you. 现在这只是一个使用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