[英]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.