简体   繁体   中英

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

Or:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM