簡體   English   中英

如何用自然數替換二進制數組中的1,同時保持0的位置?

[英]How can I replace 1s in a binary array with natural numbers, maintaining the position of 0s?

我正在使用Numpy和SciPy。 我有兩個數組,第一個是二進制數組,第二個數組是從ab的連續自然數范圍,例如

mask = np.array([1, 1, 1, 1, 0, 0, 1, 0]) # length of 8, with 5 ones and 3 zeros
vals = np.array([2, 3, 4, 5, 6, 7, 8, 9]) # length of 8, only first 5 values will be used in this case - corresponding to the 5 ones in the first array

我想將第二個數組中的值替換為第一個數組中的1(按順序保留),例如,本示例場景中所需的結果將是:

result = [2,3,4,5,0,0,6,0]

我已經用NumPy掩碼數組和vectorise函數嘗試了不同的方法。 我當前的解決方案如下,但是為了維持狀態,我不得不引入一個全局變量!

global count
count = 0
def func(a,b):
    global count
    if a ==1:
        return b - count
    else:
        count +=1
        return 0
v_func = np.vectorize(func)
result = v_func(mask, vals)
print result

有沒有更優雅的方法(理想情況下使用NumPy)呢?

(請注意,我正在使用的實際數組非常大,因此我的解決方案需要對消耗的內存量敏感-顯然我可以轉換為稀疏數組,但是我仍然遇到幾次內存錯誤試圖找到不同的解決方案。)

這是一種方法:

In [15]: result = np.zeros_like(vals)

In [16]: result[mask > 0] = vals[:mask.sum()]

In [17]: result
Out[17]: array([2, 3, 4, 5, 0, 0, 6, 0])

這是一個襯板,盡管我必須說這不是一種優化的方法,也不是很優雅。 但是您可以出於實踐目的對其進行檢查。

a = [1, 1, 1, 1, 0, 0, 1, 0]
b = [2, 3, 4, 5, 6, 7, 8, 9]

c = [b[sum(a[:i])] if a[i] else 0 for i in range(len(a))]
print c
# Gives [2, 3, 4, 5, 0, 0, 6, 0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM