Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading