user12177026
user12177026

Reputation:

Pandas, efficient way to get a rows below and and above zero values

I have a data frame that contains some cells with a zero, I want to handle those in a way that involves getting the column mean and the last row above the zero and the first one after.

I know how to get the mean with dropping the zeros. my question is, how can I get the rows I mentioned?

sample DataFrame

2020-09-15    211.03
2020-09-16    213.60
2020-09-17    205.69
2020-09-18    208.65
2020-09-19    214.35 # get the value for this row
2020-09-20      0.00
2020-09-21      0.00 
2020-09-22    222.54 # and for this row

Upvotes: 0

Views: 197

Answers (1)

Code Different
Code Different

Reputation: 93161

Try this:

col = df['column_name']
cond = col.ne(0) & (
    col.shift().eq(0)      # row above is 0
    | col.shift(-1).eq(0)  # row below is 0
)
df.loc[cond]

Upvotes: 2

Related Questions