gpt4 book ai didi

python - 迭代 `np.where` 的输出

转载 作者:太空狗 更新时间:2023-10-30 00:36:13 25 4
gpt4 key购买 nike

我有一个 3D 数组并使用 np.where 来查找满足特定条件的元素。 np.where 的输出是三个一维数组的元组,每个数组都给出了沿单个轴的索引。我想遍历此输出并打印出矩阵中满足条件的每个点的索引。

一种方法是:

indices = np.where(myarray == 0)
for i in range(0, len(indices[0])):
print indices[0][i], indices[1][i], indices[2][i]

但是,看起来有点麻烦,我想知道有没有更好的方法?

最佳答案

使用zip

indices = zip(*np.where(myarray == 0))

然后你可以做

for i, j, k in indices:
print ...

例如,

In [1]: x = np.random_integers(0, 1, (3, 3, 3))
In [2]: np.where(x) # you want np.where(x==0)
Out[2]: (array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2]),
array([0, 1, 1, 2, 2, 0, 0, 1, 1, 2]),
array([1, 0, 1, 0, 1, 1, 2, 0, 2, 2]))
In [3]: zip(*np.where(x))
Out[3]: [(0, 0, 1),
(0, 1, 0),
(0, 1, 1),
(0, 2, 0),
(0, 2, 1),
(1, 0, 1),
(1, 0, 2),
(1, 1, 0),
(1, 1, 2),
(2, 2, 2)]

关于python - 迭代 `np.where` 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com