Home > front end >  pandas remove entire row if it contains negative values
pandas remove entire row if it contains negative values

Time:09-26

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

CodePudding user response:

Or:

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

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

CodePudding user response:

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
  • Related