Skip to content Skip to sidebar Skip to footer

Drop Rows In Pandas Dataframe Based On Columns Value

I have a dataframe like this : cols = [ 'a','b'] df = pd.DataFrame(data=[[NaN, -1, NaN, 34],[-32, 1, -4, NaN],[4,5,41,14],[3, NaN, 1, NaN]], columns=['a', 'b', 'c', 'd']) I want t

Solution 1:

IIUC, you actually want

>>> df[((df[cols] > 0) | df[cols].isnull()).all(axis=1)]
   abcd245411433NaN1NaN

Right now you're getting "if they're all positive" or "any are null". You want "if they're all (positive or null)". (Replace > 0 with >=0 for nonnegativity.)

And since NaN isn't positive, we could simplify by flipping the condition, and use something like

>>>df[~(df[cols] <= 0).any(axis=1)]
   a   b   c   d
2  4   5  41  14
3  3 NaN   1 NaN

Post a Comment for "Drop Rows In Pandas Dataframe Based On Columns Value"