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

如何解决numpy.ndarray索引报错:仅整数标量数组可转标量索引

解决索引图片时的「only integer scalar arrays can be converted to a scalar index」错误

嘿,我来帮你搞定这个问题!咱们先拆解下为啥会报错:

你用np.argwhere(c == n)得到的结果是二维numpy数组,举个例子,你的c = [1,1,1,0,1,2,2,3,4,1,3],当n=1时,np.argwhere(c==1)会返回:

array([[0],
       [1],
       [2],
       [4],
       [9]])

遍历这个结果时,每个i其实是形状为(1,)的小数组(比如array([0])),而你的images是列表,列表只接受整数标量当索引,直接用数组当然会报错啦。

至于你换成images[n]能运行但结果不对,是因为n是聚类的编号(0、1、2、3、4),你只是取了列表里第n个位置的图片,并不是当前聚类下所有对应索引的图片,自然不符合预期。

两种简单的解决办法:

方法1:遍历数组时提取标量值

每个i是单元素数组,直接取它的第一个元素就能得到整数:

import numpy as np
import os

DIR_NAME = "你的图片目录路径"
c = np.array([1, 1, 1, 0, 1, 2, 2, 3, 4, 1, 3])
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)

for n in range(num_clusters):
    # 获取当前聚类的所有索引(二维数组)
    cluster_indices = np.argwhere(c == n)
    for i in cluster_indices:
        # 把数组转成整数标量
        idx = i[0]
        # 现在可以正常索引images了
        target_image = images[idx]
        # 执行你的打印或其他操作
        print(f"聚类{n}对应的图片:{target_image}")

方法2:先把二维数组转成一维数组

用flatten()把np.argwhere的结果转成一维整数数组,遍历的时候直接拿到整数:

import numpy as np
import os

DIR_NAME = "你的图片目录路径"
c = np.array([1, 1, 1, 0, 1, 2, 2, 3, 4, 1, 3])
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)

for n in range(num_clusters):
    # 转成一维整数数组
    cluster_indices = np.argwhere(c == n).flatten()
    for idx in cluster_indices:
        # idx已经是整数啦
        target_image = images[idx]
        print(f"聚类{n}对应的图片:{target_image}")

小提醒

要确保images列表的顺序和聚类标签c的顺序是一一对应的哦——也就是c的第k个标签,正好对应images里的第k张图片,不然索引出来的图片还是会不对~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:48:38