简体   繁体   中英

How to replace NaNs by preceding values plus some constant , in pandas DataFrame?

Pandas example data frame

    id   age   
0   1     2   
1   4     NaN 
2 NaN     NaN   
3   5     16
4   6     21
5   7     NaN

expected output

id   age   
0   1     2   
1   4     7 
2 NaN     11   
3   5     16
4   6     21
5   7     26

here if i want fill missing age , with previous age + 5 , how to do that ?

Is this what you need ?

df.age.ffill()+df.age.groupby(df.age.notnull().cumsum()).cumcount()*5
Out[539]: 
0     2.0
1     7.0
2    12.0
3    16.0
4    21.0
5    26.0
dtype: float64

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