Pandas : Remove rows with 0 value in the last 3 columns regardless of their name

Viewed 28

I have a data frame:

df1 = pd.DataFrame({'Region': ['LCA', 'BCC', 'AAC'], 'Jul': [233, 0, 0],'Aug': [345, 0, 0],'Sep': [366, 0, 0]  })

enter image description here

I would like to drop rows with 0 in the last 3 columns regardless of their names as the names can change. The expected result would be: enter image description here

How do I do this?

1 Answers

You can use boolean indexing:

out = df1[~df1.iloc[:, -3:].eq(0).all(1)]

output:

  Region  Jul  Aug  Sep
0    LCA  233  345  366

breaking it down:

# select last 3 columns by position
df1.iloc[:, -3:]

# compare to 0
.eq(0)

# are all booleans True? (i.e. are all values 0?)
.all(1)

# negate boolean
~

Alternative:

df1[df1.iloc[:, -3:].ne(0).any(1)]

Same as above but keeping the rows where any value is not 0

Related