且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用索引填充数组中的一维numpy数组

更新时间:2022-12-09 08:56:06

实现的诀窍是,我们将在初始化为零的int数组的每个起点放置1s,在每个终点放置-1s .接下来是实际的技巧,因为我们会对其进行累计求和,从而为bin(开始-停止对)边界所覆盖的位置提供非零数字.因此,最后一步是寻找非零值,以将最终输出作为布尔数组.因此,我们将有两个向量化的解决方案,其实现如下所示-

The trick for the implementation to follow is that we would put 1s at every start points and -1s at every end points on a zeros initialized int array. The actual trick comes next, as we would cumulatively sum it, giving us non-zero numbers for the positions covered by the bin (start-stop pair) boundaries. So, the final step is to look for non-zeros for a final output as a boolean array. Thus, we would have two vectorized solutions, with their implementations shown below -

def filled_array(start, end, length):
    out = np.zeros((length), dtype=int)
    np.add.at(out,start,1)
    np.add.at(out,end,-1)
    return out.cumsum()>0

def filled_array_v2(start, end, length): #Using @Daniel's suggestion
    out =np.bincount(start, minlength=length) - np.bincount(end, minlength=length)
    return out.cumsum().astype(bool)

样品运行-

In [2]: start
Out[2]: array([ 4,  7,  5, 15])

In [3]: end
Out[3]: array([12, 12,  7, 17])

In [4]: out = filled_array(start, end, length=20)

In [7]: pd.DataFrame(out) # print as dataframe for easy verification
Out[7]: 
        0
0   False
1   False
2   False
3   False
4    True
5    True
6    True
7    True
8    True
9    True
10   True
11   True
12  False
13  False
14  False
15   True
16   True
17  False
18  False
19  False