tags:

views:

287

answers:

1

If there is any possibility to make this code simpler, I'd really appreciate it! I am trying to get rid of rows with zeros. The first column is date. If all other columns are zero, they have to be deleted. Number of columns varies.

import numpy as np

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

numpy.extract docs

+3  A: 

You can avoid the list comprehension and instead use fancy indexing:

#!/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 a view with the first column removed. r[:,1:].any(axis=1) is a boolean array, which you can then use as a "fancy index"

unutbu
Ugh, I can't read this. Please format as "Code Sample". Edit your text, select the code, and click on the button that looks like "101/010".
steveha
This is a promising answer, but I don't think it is quite correct yet. He wants rows compressed if they are *all* zeroes, not if any single value is zero.
steveha
Okay, I've modified my code per steveha's comment
unutbu
Beautiful! I like it.
steveha
absolutely what I needed, thanks a lot, should have known ndarray indexing better!
maplpro