简体   繁体   中英

Pandas dataframe drop rows by condition

I use Pandas. I have DataFrame.

I want to delete rows according to the same conditions.

bool_mask = (df['a'] == 'aaa') & \
            (df['b'] == '') & \
            (df['c'] == '') & \
            (df['d'] == '') & \
            (df['e'] == '') & \
            (df['f'] == '') & \
            (df['m'] == '') & \
            (df['n'] == '') & \
            (df['w'] == '')

df = df[~bool_mask]

Please tell me if there is a prettier / faster solution?

I think you may use all on combining columns compared to ''

bool_mask = (df['a'] == 'aaa') & \
            (df[['b', 'c', 'd', 'e', 'f', 'm', 'n', 'w']] == '').all(1)

df = df[~bool_mask]

We can cut it down as below , find all other columns which equal to '' and columns a equal to 'aaa' is the target :

# make whole df equal to '' then sum all of them by row 
# then we at least need 8 blank 
# then apply the 2nd condition df.a should be equal to 'aaa' 
m=(df=='').sum(1).eq(8)&df.a.eq('aaa')

Or

m=df.drop('a',1).eq('').all(1)&df.a.eq('aaa')

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