Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas replace zeros with previous non zero value

Tags:

python

pandas

I have the following dataframe:

index = range(14) data = [1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2, 1] df = pd.DataFrame(data=data, index=index, columns = ['A']) 

How can I fill the zeros with the previous non-zero value using pandas? Is there a fillna that is not just for "NaN"?.

The output should look like:

[1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1] 

(This question was asked before here Fill zero values of 1d numpy array with last non-zero values but he was asking exclusively for a numpy solution)

like image 504
Gabriel Avatar asked Oct 21 '15 13:10

Gabriel


People also ask

How do you use Ffill in pandas?

Pandas DataFrame ffill() Method The ffill() method replaces the NULL values with the value from the previous row (or previous column, if the axis parameter is set to 'columns' ).

How do you backfill pandas?

bfill() is used to backward fill the missing values in the dataset. It will backward fill the NaN values that are present in the pandas dataframe.


1 Answers

You can use replace with method='ffill'

In [87]: df['A'].replace(to_replace=0, method='ffill') Out[87]: 0     1 1     1 2     1 3     2 4     2 5     4 6     6 7     8 8     8 9     8 10    8 11    8 12    2 13    1 Name: A, dtype: int64 

To get numpy array, work on values

In [88]: df['A'].replace(to_replace=0, method='ffill').values Out[88]: array([1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2, 1], dtype=int64) 
like image 126
Zero Avatar answered Sep 17 '22 15:09

Zero