【问题标题】:Get indices from one randomly chosen true element in a boolean array从布尔数组中一个随机选择的真实元素中获取索引
【发布时间】:2021-04-12 18:38:11
【问题描述】:

我有一个布尔数组,我想从中获得一个随机选择的等于 True 的元素的索引。输出应该是一个包含该元素的 (x,y,z) 索引的元组。

有没有更优雅和/或更有效的方法来代替以下操作?

import numpy as np
rng = np.random.RandomState(42)

# create a random 3D boolean array
m = rng.choice(a=[False, True],size=(3,3,3))

# get (x,y,z) from one random cell in the boolean array which equals True
indices_where_true = np.where(m)
random_int = rng.randint(len(indices_where_true[0]),size=1)
random_index = (indices_where_true[0][random_int][0],
                indices_where_true[1][random_int][0],
                indices_where_true[2][random_int][0])

【问题讨论】:

    标签: python numpy random


    【解决方案1】:

    使用np.argwhere 代替np.where

    true_idx = np.argwhere(m)
    
    random_idx = rng.randint(len(true_idx),size=1)
    random_index = true_idx[random_idx]
    # array([[0, 1, 2]])
    

    【讨论】:

    • 这似乎是最易读的解决方案。请注意,我要求一个元组,也许你可以在你的帖子中添加以下(或更好的选择):random_index = true_idx[random_idx][0] random_index = (random_index[0],random_index[1],random_index[2])
    【解决方案2】:

    numpy.where 文档中的注释指出:

    当只提供condition 时,该函数是np.asarray(condition).nonzero() 的简写。应该首选直接使用nonzero,因为它对子类表现正确。

    所以你应该用nonzero 替换where。在对随机整数进行采样后,您可以使用numpy.take 沿indices_where_true 的第一轴获取该索引处的所有元素来选择坐标:

    from numpy import random
    rng = np.random.RandomState(42)
    
    # create a random 3D boolean array
    m = rng.choice(a=[False, True],size=(3,3,3))
    
    # get (x,y,z) from one random cell in the boolean array which equals True
    indices_where_true = np.nonzero(m)
    random_int = rng.randint(len(indices_where_true[0]),size=1)
    random_index = np.take(indices_where_true, random_int, axis=1)
    

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多