Sign Up

Sign In

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

Filter rows of pandas dataframe whose values are lower than 0

  • 2

I have a pandas dataframe like this

df = pd.DataFrame(data=[[21, 1],[32, -4],[-4, 14],[3, 17],[-7,NaN]], columns=['a', 'b'])
df

I want to be able to remove all rows with negative values in a list of columns and conserving rows with NaN.

In my example there is only 2 columns, but I have more in my dataset, so I can’t do it one by one.

Share

1 Answer

  1. If you want to apply it to all columns, do df[df > 0] with dropna():

    >>> df[df > 0].dropna()
        a   b
    0  21   1
    3   3  17
    

    If you know what columns to apply it to, then do for only those cols with df[df[cols] > 0]:

    >>> cols = ['b']
    >>> df[cols] = df[df[cols] > 0][cols]
    >>> df.dropna()
        a   b
    0  21   1
    2  -4  14
    3   3  17
    
    • 0
Leave an answer

Leave an answer

Browse

close