gpt4 book ai didi

python - 如何删除 2D 矩阵中值为 0 的前 n 列/行?

转载 作者:行者123 更新时间:2023-11-30 22:12:48 26 4
gpt4 key购买 nike

引用上一个问题:

Remove all-zero rows in a 2D matrix

import numpy as np

data = np.array([[4, 1, 1, 2, 0, 4],
[3, 4, 3, 1, 4, 4],
[1, 4, 3, 1, 0, 0],
[0, 4, 4, 0, 4, 3],
[0, 0, 0, 0, 0, 0]])

data = data[~(data==0).all(1)]
print(data)

输出:

    [[4 1 1 2 0 4]
[3 4 3 1 4 4]
[1 4 3 1 0 0]
[0 4 4 0 4 3]]

到目前为止一切顺利,但是如果我添加空列怎么办?

 data = np.array([[0, 4, 1, 1, 2, 0, 4],
[0, 3, 4, 3, 1, 4, 4],
[0, 0, 1, 4, 3, 1, 0],
[0, 0, 4, 4, 0, 4, 3],
[0, 0, 0, 0, 0, 0, 0]])

输出为

          [[0 4 1 1 2 0 4]
[0 3 4 3 1 4 4]
[0 1 4 3 1 0 0]
[0 0 4 4 0 4 3]]

这不是我想要的。

基本上,如果我的矩阵是:

            [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 4, 1, 1, 2, 0, 4, 0],
[0, 0, 3, 4, 3, 1, 4, 4, 0],
[0, 0, 1, 4, 3, 1, 0, 0, 0],
[0, 0, 0, 4, 4, 0, 4, 3, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]

我期望的输出是

        [[4 1 1 2 0 4]
[3 4 3 1 4 4]
[1 4 3 1 0 0]
[0 4 4 0 4 3]]

最佳答案

这是一种方法 -

def reduced_box(a):
# Store shape info
M,N = a.shape

# Mask of valid places in the array
mask = a!=0

# Get boolean array with at least a valid one per row
m_col = mask.any(1)

# Get the starting and ending valid rows with argmax.
# More info : https://stackoverflow.com/a/47269413/
r0,r1 = m_col.argmax(), M-m_col[::-1].argmax()

# Repeat for cols
m_row = mask.any(0)
c0,c1 = m_row.argmax(), N-m_row[::-1].argmax()

# Finally slice with the valid indices as the bounding box limits
return a[r0:r1,c0:c1]

示例运行 -

In [210]: a
Out[210]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 4, 1, 0, 2, 0, 4, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 4, 0, 1, 0, 0, 0],
[0, 0, 0, 4, 0, 0, 4, 3, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])

In [211]: reduced_box(a)
Out[211]:
array([[4, 1, 0, 2, 0, 4],
[0, 0, 0, 0, 0, 0],
[1, 4, 0, 1, 0, 0],
[0, 4, 0, 0, 4, 3]])

关于python - 如何删除 2D 矩阵中值为 0 的前 n 列/行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966579/

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