Search code examples
pythonpandasdataframeseries

How to forward propagate/fill a specific value in a Pandas DataFrame Column/Series?


I have a boolean column in a dataframe that looks like the following:

True
False
False
False
False
True
False
False
False

I want to forward propagate/fill the True values n number of times. e.g. 2 times:

True
True
True
False
False
True
True
True
False

the ffill does something similar for NaN values, but I can't find anything for a specific value as described. Is the easiest way to do this just to do a standard loop and just iterate over the rows and modify the column in question with a counter?

Each row is an equi-distant time series entry

EDIT:

The current answers all solve my specific problem with a bool column, but one answer can be modified to be more general purpose:

>> s = pd.Series([1, 2, 3, 4, 5, 1, 2, 3])
0    1
1    2
2    3
3    4
4    5
5    1
6    2
7    3

>> condition_mask = s == 2
>> s.mask(~(condition_mask)).ffill(limit=2).fillna(s).astype(int)

0    1
1    2
2    2
3    2
4    5
5    1
6    2
7    2

Solution

  • You can still use ffill but first you have to mask the False values

    s.mask(~s).ffill(limit=2).fillna(s)
    

    0     True
    1     True
    2     True
    3    False
    4    False
    5     True
    6     True
    7     True
    8    False
    Name: 0, dtype: bool