我有非常稀疏的矩阵,所以我想提取具有非零值的矩阵的最小矩形区域。我知道 numpy.nonzero(a) 为您提供非零元素的索引,但如何使用它来提取包含这些索引处的矩阵元素的子矩阵。
举个例子,这就是我的目标:
>>> test
array([[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 0]])
>>> np.nonzero(test)
(array([1, 1, 1, 1, 2, 2]), array([1, 2, 3, 4, 2, 3]))
>>> submatrix(test)
array([[1, 1, 1, 1],
[0, 1, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
有谁知道在 numpy 中执行此操作的简单方法吗?谢谢。
看起来您正在寻找包含所有非零元素的矩阵的最小区域。如果这是真的,这里有一个方法:
import numpy as np
def submatrix(arr):
x, y = np.nonzero(arr)
# Using the smallest and largest x and y indices of nonzero elements,
# we can find the desired rectangular bounds.
# And don't forget to add 1 to the top bound to avoid the fencepost problem.
return arr[x.min():x.max()+1, y.min():y.max()+1]
test = np.array([[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 0]])
print submatrix(test)
# Result:
# [[1 1 1 1]
# [0 1 1 0]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2790 次 |
最近记录: |