Numpy.extract and numpy.any, is it possible to do this in an easier way?

If there is an opportunity to make this code simpler, I would really appreciate it! I am trying to get rid of strings with zeros. The first column is the date. If all other columns are zero, they need to be removed. The number of columns changes.

import numpy as np

condition = [ np.any( list(x)[1:] ) for x in r]
r = np.extract( condition, r )

      

numpy.extract

docs

+2


source to share


1 answer


You can avoid list comprehension and use fancy indexing instead:

#!/usr/bin/env python
import numpy as np
import datetime
r=np.array([(datetime.date(2000,1,1),0,1),
            (datetime.date(2000,1,1),1,1),
            (datetime.date(2000,1,1),1,0),
            (datetime.date(2000,1,1),0,0),                        
            ])
r=r[r[:,1:].any(axis=1)]
print(r)
# [[2000-01-01 0 1]
#  [2000-01-01 1 1]
#  [2000-01-01 1 0]

      



if r is an ndarray then r [:, 1:] is the view with the first column removed. r [:, 1:]. any (axis = 1) is a boolean array which can then be used as a "fantastic index"

+4


source







All Articles