How can you turn an index array into a mask array in Numpy?

前端 未结 4 1079
孤街浪徒
孤街浪徒 2020-12-14 17:04

Is it possible to convert an array of indices to an array of ones and zeros, given the range? i.e. [2,3] -> [0, 0, 1, 1, 0], in range of 5

I\'m trying to automate so

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 17:29

    For a single dimension, try:

    n = (15,)
    index_array = [2, 5, 7]
    mask_array = numpy.zeros(n)
    mask_array[index_array] = 1
    

    For more than one dimension, convert your n-dimensional indices into one-dimensional ones, then use ravel:

    n = (15, 15)
    index_array = [[1, 4, 6], [10, 11, 2]] # you may need to transpose your indices!
    mask_array = numpy.zeros(n)
    flat_index_array = np.ravel_multi_index(
        index_array,
        mask_array.shape)
    numpy.ravel(mask_array)[flat_index_array] = 1
    

提交回复
热议问题