Youpi14
Youpi14

Reputation: 21

How to add 1 to previous data if NaN in pandas

I was wondering if it is possible to add 1 (or n) to missing values in a pandas DataFrame / Series.

For example:
1
10
nan
15
25
nan
nan
nan
30

Would return :
1
10
11
15
25
26
27
28
30

Thank you,

Upvotes: 0

Views: 465

Answers (1)

ALollz
ALollz

Reputation: 59549

Use .ffill + the result of a groupby.cumcount to determine n

df[0].ffill() + df.groupby(df[0].notnull().cumsum()).cumcount()

0     1.0
1    10.0
2    11.0
3    15.0
4    25.0
5    26.0
6    27.0
7    28.0
8    30.0
dtype: float64

Upvotes: 2

Related Questions