Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas fillna with an incremented value

I have a dataframe with a column of sequential but not adjacent numbers and missing values.

I'd like to use the fillna function to fill in the missing values with an incremented value from the previous non-missing row.

Here's a simplified table:

index  my_counter
0      1
1      2
2      NaN
3      3
4      NaN
5      NaN
6      8

I'd like to fill in my_counter as such:

index  my_counter
0      1
1      2
2      2.1
3      3
4      3.1
5      3.2
6      8

How can I accomplish this task?

like image 666
Nowhere Fast Avatar asked Oct 20 '25 02:10

Nowhere Fast


1 Answers

IIUC ffill with groupby cumcount

df.my_counter.ffill()+df.groupby(df.my_counter.notnull().cumsum()).cumcount()/10
Out[92]: 
0    1.0
1    2.0
2    2.1
3    3.0
4    3.1
5    3.2
6    8.0
dtype: float64
like image 83
BENY Avatar answered Oct 22 '25 04:10

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!