输入:
- 数组长度(整数)
- 索引(集合或列表)
输出:
一个 bool 型 numpy 数组,索引值为 1,其他索引值为 0。
例子:
输入:array_length=10, indexes={2,5,6}
输出:
[0,0,1,0,0,1,1,0,0,0]
这是我的一个简单实现:
def indexes2booleanvec(size, indexes):
v = numpy.zeros(size)
for index in indexes:
v[index] = 1.0
return v
有没有更优雅的实现方式?
最佳答案
一种方法是避免循环
In [7]: fill = np.zeros(array_length) # array_length = 10
In [8]: fill[indexes] = 1 # indexes = [2,5,6]
In [9]: fill
Out[9]: array([ 0., 0., 1., 0., 0., 1., 1., 0., 0., 0.])
关于python - (Numpy) bool 数组的索引列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29982036/