Remove all zero rows and columns in one go in Python
Question:
I want to remove all zero rows and columns in one line from the array A1
. I present the current and expected outputs.
import numpy as np
A1=np.array([[0, 0, 0],
[0, 1, 2],
[0, 3, 4]])
A1 = A1[~np.all(A1 == 0, axis=0)]
print([A1])
The current output is
[array([[0, 1, 2],
[0, 3, 4]])]
The expected output is
[array([[1, 2],
[3, 4]])]
Answers:
Not really sure your example works, but given the description in the title – for a matrix matrix
, you can use
mask = matrix != 0
new_matrix = matrix[np.ix_(mask.any(1), mask.any(0))]
you can check out this post about np.ix_
I want to remove all zero rows and columns in one line from the array A1
. I present the current and expected outputs.
import numpy as np
A1=np.array([[0, 0, 0],
[0, 1, 2],
[0, 3, 4]])
A1 = A1[~np.all(A1 == 0, axis=0)]
print([A1])
The current output is
[array([[0, 1, 2],
[0, 3, 4]])]
The expected output is
[array([[1, 2],
[3, 4]])]
Not really sure your example works, but given the description in the title – for a matrix matrix
, you can use
mask = matrix != 0
new_matrix = matrix[np.ix_(mask.any(1), mask.any(0))]
you can check out this post about np.ix_