Shrilaxmi M S
Shrilaxmi M S

Reputation: 171

pandas remove entire row if it contains negative values

How to remove the entire row if it contains negative values?

 df = pd.DataFrame({'col1': [1,-2,3,4],
                    'col2': [-1, -2, -3, 4],
                    'col4': [1,-2,3,4]})

output

       col1  col2  col4
        1    -1     1
        3    -3     3
        4     4     4

Upvotes: 1

Views: 1454

Answers (2)

I'mahdi
I'mahdi

Reputation: 24059

Or:

>>> df[~df.lt(0).all(axis=1)]

   col1  col2  col4
0     1    -1     1
2     3    -3     3
3     4     4     4

Upvotes: 3

Corralien
Corralien

Reputation: 120469

Keep rows those at least one value is positive:

df = df[df.ge(0).any(axis=1)]
print(df)

   col1  col2  col4
0     1    -1     1
2     3    -3     3
3     4     4     4

Or drop rows where all values are negative:

df = df.drop(df[df.lt(0).all(axis=1)].index)
print(df)

   col1  col2  col4
0     1    -1     1
2     3    -3     3
3     4     4     4

Upvotes: 2

Related Questions