You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查找numpy数组中True值的索引及np.random.choice使用问题

解决二维numpy布尔数组的np.random.choice使用问题

np.random.choice仅支持输入一维数组,直接传入二维数组会报错,针对你的二维布尔数组,可根据需求选择以下处理方式:

方式一:随机选择数组中的任意元素

先将二维数组扁平化转为一维,再调用np.random.choice:

import numpy as np

a = np.array([
    [False, False, False, False, False, False, False, False, False, False],
    [False, False, False, False, False, False, False, False, False, False],
    [False, False, False, True, True, False, False, False, False, False]
])

# 扁平化二维数组
flat_a = a.flatten()
# 随机选取一个元素
random_item = np.random.choice(flat_a)

方式二:随机选择一个值为True的元素位置

如果需要定位数组中True元素的位置,可先获取所有True的索引,再随机选取:

# 获取所有True元素的二维坐标
true_positions = np.argwhere(a)
# 随机选择一个坐标的索引
random_idx = np.random.choice(true_positions.shape[0])
# 得到选中的True元素位置
selected_pos = true_positions[random_idx]
# 也可直接取出该位置的元素(结果必为True)
selected_true = a[selected_pos[0], selected_pos[1]]

也可以通过扁平化索引实现:

# 生成扁平化后的全局索引
all_indices = np.arange(a.size)
# 筛选出对应True元素的扁平化索引
true_flat_indices = all_indices[a.flatten()]
# 随机选一个扁平化索引
random_flat_idx = np.random.choice(true_flat_indices)
# 转换为二维坐标
row = random_flat_idx // a.shape[1]
col = random_flat_idx % a.shape[1]
selected_pos = (row, col)

内容的提问来源于stack exchange,提问作者user20530243

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:50:51