Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23189

Pandas replace zero as the nearest average non-zero value

$
0
0

I have a dataframe:

 df = pd.DataFrame({'A':[0,0,15,0,0,12,0,0,0,5]})

And I want to replace the 0 value with the nearest non zero value,

For example, the first value is 0, then I find the the nearest non-zero value is 15, so I replace it as 15, then the data becomes:[15,0,15,0,0,12,0,0,0,5],

Then for all the value except first one, I need to find the both side of the nearest non-zero value, and average them. So for the second 0, it would be (15+15)/2; And the third zero would be (15+12)/2

I only know how to replace zero to the nearest value by:

df['A'].replace(to_replace=0, method='ffill')0     01     02    153    154    155    126    127    128    129     5

But the first two zero value cannot be replaced, and this way is not getting the average value.


Viewing all articles
Browse latest Browse all 23189

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>