Numpy 二进制矩阵 - 获取 True 元素的行和列 [英] Numpy binary matrix - get rows and columns of True elements
本文介绍了Numpy 二进制矩阵 - 获取 True 元素的行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二进制 numpy 2D 数组,比如说,
I have a binary numpy 2D array, say,
import numpy as np
arr = np.array([
# Col 0 Col 1 Col 2
[False, False, True], # Row 0
[True, False, False], # Row 1
[True, True, False], # Row 2
])
我想要矩阵中每个 True
元素的行和列:
I want the row and column of each True
element in the matrix:
[(0, 2), (1, 0), (2, 0), (2, 1)]
我知道我可以通过迭代做到这一点:
I know I can do this through iteration:
links = []
nrows, ncols = arr.shape
for i in xrange(nrows):
for j in xrange(ncols):
if arr[i, j]:
links.append((i, j))
有没有更快或更直观的方法?
Is there a faster or more intuitive way?
推荐答案
您正在寻找 np.argwhere
-
You are looking for np.argwhere
-
np.argwhere(arr)
样品运行 -
In [220]: arr
Out[220]:
array([[False, False, True],
[ True, False, False],
[ True, True, False]], dtype=bool)
In [221]: np.argwhere(arr)
Out[221]:
array([[0, 2],
[1, 0],
[2, 0],
[2, 1]])
这篇关于Numpy 二进制矩阵 - 获取 True 元素的行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文