访问布尔Numpy矩阵的所有非对角元素
假设有一个对角矩阵 M:
#import numpy as np
M = np.matrix(np.eye(5, dtype=bool))
有没有人知道一个简单的方法来获取所有非对角线的元素,也就是所有值为 False
的元素?在 R
语言中,我可以通过执行
M[!M]
不幸的是,这在 Python 中是无效的。
2 个回答
4
你可以试试把np.extract和np.eye结合起来使用。比如说:
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
np.extract(1 - np.eye(3), M)
# result: array([2, 3, 4, 6, 7, 8])
在你的例子中,这几乎就是一个单位矩阵:
M = np.matrix(np.eye(5, dtype=bool))
np.extract(1 - np.eye(5), M)
#result:
array([False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False], dtype=bool)
8
你需要使用按位取反运算符:
M[~M]