使用重叠的索引片段为numpy数组赋值

时间:2017-08-21 20:40:51

标签: python numpy

我想为数组的某些段分配值。 我已经将段的索引作为元组(start_idx,end_idx)。 片段可以叠加或者是彼此的子片段。

a = np.zeros(12)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])
a[segments] = 1

结果是:

a
>> array([1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0])

如何屏蔽所有段以获得此输出:

a
>> array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0])

4 个答案:

答案 0 :(得分:2)

这是一种矢量化方法,其思想是从this post -

借来的
def segment_arr(segments, L): # L being length of output array
    s = np.zeros(L,dtype=int)
    stop = segments[:,1]+1
    np.add.at(s,segments[:,0],1)
    np.add.at(s,stop[stop<len(s)],-1)
    return (s.cumsum()>0).astype(int)

示例运行 -

In [298]: segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])

In [299]: segment_arr(segments, L=12)
Out[299]: array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0])

答案 1 :(得分:1)

试试这个:

a = np.zeros(10)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])
a[range(3)+range(1,2)+range(6,8)+range(8,10)] = 1
print (a)

答案 2 :(得分:1)

一种选择是简单地遍历,并将范围转换为实际索引:

a = np.zeros(10)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])

a[[i for s in segments for i in range(*s)]] = 1    
a
# array([ 1.,  1.,  1.,  0.,  0.,  0.,  1.,  1.,  1.,  1.])

答案 3 :(得分:1)

提到一个简单的解决方案:在for上使用segments循环并分配给切片:

import numpy as np
a = np.zeros(12)
segments = np.array([(0, 3), (1, 2), (6, 8), (8, 10)])

for seg in segments.tolist():  # the "tolist" is just an optimization here, you *could* omit it.
    a[seg[0]: seg[1]+1] = 1    # or just "seq[1]" if you want to exclude the end point
print(a)
# array([ 1.,  1.,  1.,  1.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.])