简体   繁体   中英

Drop rows of a Pandas dataframe if the value of range columns 0

Dataframe:

df = pd.DataFrame({'a':['NA','W','Q','M'], 'b':[0,0,4,2], 'c':[0,12,0,2], 'd':[22, 3, 34, 12], 'e':[0,0,3,6], 'f':[0,2,0,0], 'h':[0,1,1,0] })
df
    a   b   c   d   e   f   h
0   NA  0   0   22  0   0   0
1   W   0   12  3   0   2   1
2   Q   4   0   34  3   0   1
3   M   2   2   12  6   0   0

I want to drop the entire row if the value of column b and all columns e contain 0

Basically I want to get something like this

a   b   c   d   e   f   h
1   W   0   12  3   0   2   1
2   Q   4   0   34  3   0   1
3   M   2   2   12  6   0   0

If want test from e to end columns and b columns added by DataFrame.assign use DataFrame.loc for selecing, test for not equal by DataFrame.ne and then if aby values match (it means no all 0 ) with DataFrame.any and last filter by boolean indexing :

df = df[df.loc[:, 'e':].assign(b = df['b']).ne(0).any(axis=1)]
print (df)
   a  b   c   d  e  f  h
1  W  0  12   3  0  2  1
2  Q  4   0  34  3  0  1
3  M  2   2  12  6  0  0

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