如何在 python 的一个数组中连接 numpy.ones 和 numpy.zeros 函数?

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

我想创建一个一维数组,它由两个输入数组定义的交替的 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 循环的更有效的方法?

这是一个使用 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()

或者,如果切片很大或者只是为了提高内存效率,我们可能希望使用仅切片的循环来分配 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')

我用地图做了这个。 在我看来,代码中最耗时的部分是连接,因此我将其替换为 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)

使用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])