5

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?

2
  • 1
    Since your whole array contains solely zeros, you can just do data = np.array([]). Sep 23, 2017 at 20:33
  • What's the desired result? A copy-n-paste of your code doesn't change data. idx is empty. It almost looks like you want to delete rows that are entirely zeros. np.delete(data, [0,1,2,3,9,11,12], axis=1) would remove selected columns.
    – hpaulj
    Sep 23, 2017 at 21:24

2 Answers 2

9

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.

1
  • Note that despite altering dimensions, @Daniel's answer does succeed in removing zeros in 2d and higher cases
    – Eric
    Sep 24, 2017 at 7:42
7

Use logical indexing:

data = np.zeros(500)
data = data[data!=0]
1
  • takes 4 sekonds
    – user8580127
    Sep 23, 2017 at 21:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.