Luke M.
Luke M.

Reputation: 13

Delete specific Values of an Array: Python

I have an array of the shape (1179648, 909). The problem is that some rows are filled with 0's only. I am checking for this as follows:

for i in range(spectra1Only.shape[0]):
    for j in range(spectra1Only.shape[1]):
        if spectra1Only[i,j] == 0:

I now want to remove the whole row of [i] if there is any 0 appearing to get a smaller amount of only the data needed.

My question is: what would be the best method to do so? Remove? Del? numpy.delete? Or any other method?

Upvotes: 0

Views: 73

Answers (1)

jpp
jpp

Reputation: 164823

You can use Boolean indexing with np.any along axis=1:

spectra1Only = spectra1Only[~(spectra1Only == 0).any(1)]

Here's a demonstration:

A = np.random.randint(0, 9, (5, 5))

print(A)

[[5 0 3 3 7]
 [3 5 2 4 7]
 [6 8 8 1 6]
 [7 7 8 1 5]
 [8 4 3 0 3]]

print(A[~(A == 0).any(1)])

[[3 5 2 4 7]
 [6 8 8 1 6]
 [7 7 8 1 5]]

Upvotes: 1

Related Questions