gpt4 book ai didi

python - (Numpy) bool 数组的索引列表

转载 作者:太空狗 更新时间:2023-10-30 01:54:11 25 4
gpt4 key购买 nike

输入:

  1. 数组长度(整数)
  2. 索引(集合或列表)

输出:

一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com