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

如何将np.where的返回元组转换为NumPy数组?

解决np.where返回元组,提取单独索引数组的问题

直接通过索引[0]提取元组内的numpy数组即可,具体实现如下:

import numpy as np

diff = [19, 403472, 403491, 403491, 403491, 403491, 13, 403478, 13]
# 取元组的第一个元素获取单独数组
indices = np.where(diff > np.average(diff))[0]
print(indices)
# 输出: array([1, 2, 3, 4, 5, 7], dtype=int64)

原理说明

np.where函数的返回值结构和输入数组的维度相关:

  • 对于一维数组,返回的是包含单个numpy数组的元组,这个数组就是满足条件的元素索引
  • 对于多维数组,返回的元组会包含对应每个维度的索引数组

如果需要将numpy数组转为Python原生列表,可以调用tolist()方法:

indices_list = indices.tolist()
print(indices_list)
# 输出: [1, 2, 3, 4, 5, 7]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:10:48