如何获取 numpy.ndarray 的索引
How to get the index of an numpy.ndarray
我想打印索引 i
上的图像,但出现 only integer scalar arrays can be converted to a scalar index
错误。如何将每次迭代 I
转换为 int
我试过用 images[n]
替换 images[i]
它有效,但不是我想要的结果。
c = [1 1 1 0 1 2 2 3 4 1 3]
#c here is list of cluster labels obtained after Affinity propagation
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)
for n in range(num_clusters):
print("\n --- Images from cluster #%d ---" % n)
for i in np.argwhere(c == n):
if i != -1:
print("Image %s" % images[i])
我希望输出是图像的名称,但我却得到了 TypeError: only integer scalar arrays can be converted to a scalar index
,这是因为 i
的类型是 numpy.ndarray
看看doc of np.argwhere
,它不是return一个整数列表,而是一个列表列表
x = array([[0, 1, 2], [3, 4, 5]])
np.argwhere(x>1)
>>> array([[0, 2], [1, 0], [1, 1], [1, 2]])
y = np.array([0, 1, 2, 3, 4, 6, 7])
np.argwhere(y>3)
>>> array([[4], [5], [6]])
因此,在不知道您的 c
是什么样子的情况下,我假设您的 i
将采用 np.array([[3]])
形式而不是整数,因此您的代码失败。在执行 i != -1
.
之前,先打印 i
进行测试和提取(例如 i[0][0]
并测试它是 non-empty)所需的索引
元
最佳做法是 post 一个最小的可重构示例,即其他人应该能够 copy-paste 代码并 运行 它。此外,如果您 post 至少有几行回溯(而不仅仅是错误),我们将能够准确判断错误发生的位置。
我想打印索引 i
上的图像,但出现 only integer scalar arrays can be converted to a scalar index
错误。如何将每次迭代 I
转换为 int
我试过用 images[n]
替换 images[i]
它有效,但不是我想要的结果。
c = [1 1 1 0 1 2 2 3 4 1 3]
#c here is list of cluster labels obtained after Affinity propagation
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)
for n in range(num_clusters):
print("\n --- Images from cluster #%d ---" % n)
for i in np.argwhere(c == n):
if i != -1:
print("Image %s" % images[i])
我希望输出是图像的名称,但我却得到了 TypeError: only integer scalar arrays can be converted to a scalar index
,这是因为 i
的类型是 numpy.ndarray
看看doc of np.argwhere
,它不是return一个整数列表,而是一个列表列表
x = array([[0, 1, 2], [3, 4, 5]])
np.argwhere(x>1)
>>> array([[0, 2], [1, 0], [1, 1], [1, 2]])
y = np.array([0, 1, 2, 3, 4, 6, 7])
np.argwhere(y>3)
>>> array([[4], [5], [6]])
因此,在不知道您的 c
是什么样子的情况下,我假设您的 i
将采用 np.array([[3]])
形式而不是整数,因此您的代码失败。在执行 i != -1
.
i
进行测试和提取(例如 i[0][0]
并测试它是 non-empty)所需的索引
元
最佳做法是 post 一个最小的可重构示例,即其他人应该能够 copy-paste 代码并 运行 它。此外,如果您 post 至少有几行回溯(而不仅仅是错误),我们将能够准确判断错误发生的位置。