简体   繁体   中英

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. eg 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

For 2 times you could have:

s = s | s.shift(1) | s.shift(2)

You could generalize to n-times from there.

Try with rolling

n = 3
s.rolling(n, min_periods=1).max().astype(bool)
Out[147]: 
0     True
1     True
2     True
3    False
4    False
5     True
6     True
7     True
8    False
Name: s, dtype: bool

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM