MrPete MrPete - 23 days ago 10
Python Question

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?

Answer Source

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.