Pandas fillna with an incremented value

荒凉一梦 提交于 2020-06-17 04:58:26

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/52416574/pandas-fillna-with-an-incremented-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!