簡體   English   中英

如何在 python 的一個數組中連接 numpy.ones 和 numpy.zeros 函數?

[英]How to concatenate numpy.ones and numpy.zeros functions in one array on python?

我想創建一個一維數組,該數組由兩個輸入 arrays 定義的交替的 1 和 0 集組成。 例如:

import numpy as np

In1 = np.array([2, 1, 3])
In2 = np.array([1, 1, 2])

Out1 = np.array([])

for idx in range(In1.size):
    Ones = np.ones(In1[idx])
    Zeros = np.zeros(In2[idx])

    Out1 = np.concatenate((Out1, Ones, Zeros))

print(Out1)
array([1., 1., 0., 1., 0., 1., 1., 1., 0., 0.])

有沒有更有效的方法來做到這一點,不使用 for 循環?

使用np.repeat

(np.arange(1,1+In1.size+In2.size)&1).repeat(np.array([In1,In2]).reshape(-1,order="F"))
# array([1, 1, 0, 1, 0, 1, 1, 1, 0, 0])

這是一個使用cumsum的矢量化 -

L = In1.sum() + In2.sum()
idar = np.zeros(L, dtype=int)

s = In1+In2
starts = np.r_[0,s[:-1].cumsum()]
stops = In1+starts
idar[starts] = 1
idar[stops] = -1
out = idar.cumsum()

或者,如果切片很大或只是為了實現 memory 效率,我們可能希望使用僅切片的循環來分配1s -

# Re-using L, starts, stops from earlier approach
out = np.zeros(L, dtype=bool)
for (i,j) in zip(starts,stops):
    out[i:j] = 1
out = out.view('i1')

我用 map 做到了這一點。 在我看來,代碼中最耗時的部分是連接,所以我用 python 列表替換了它。 (基於

from itertools import chain
creator = lambda i: In1[i]*[1] + In2[2]*[0]
nested = list(map(creator,range(len(In1))))
flatten = np.array(list(chain(*nested)))
print(flatten)

暫無
暫無

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

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