【发布时间】: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])
【问题讨论】: