user8580127
user8580127

Reputation:

remove zeros from nparray efficiently

In the moment I am using this method:

data = np.array([[0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 6, 0, 0], [0, 0, 0, 0, 1, 2,3, 4, 5, 0, 6, 0, 0]])
index = 0
idx = []
for img in range(len(data)):
    img_raw = np.any(data[img])
    if img_raw == 0.0:
        idx.append(index)
    index+=1
data = np.delete(data, idx, axis=0)

Does somebody know a better method?

Upvotes: 5

Views: 17433

Answers (2)

keepAlive
keepAlive

Reputation: 6655

Whatever data is, Daniel answers for 1d-arrays, which appears to be sufficient in your case. If your data array is 2d, things become little bit more complicated since you cannot remove your 0s without altering the dimensions of your array. In this case, you may use mask-arrays to remove non-wanted values from your considerations, e.g.

import numpy as np
ma_data = np.ma.masked_equal(data,0)
print(ma_data)

Any calculation, say mean, std, and so on, don't consider masked values.

Upvotes: 9

Daniel
Daniel

Reputation: 42758

Use logical indexing:

data = np.zeros(500)
data = data[data!=0]

Upvotes: 7

Related Questions