首页 > 解决方案 > Pandas: Is there anyway to fill Nan's in a column with continuous dates

问题描述

I have a dataframe like so:

  Date         Day_number
   10/03/2020     1
   11/03/2020     2
   12/03/2020     3
   13/03/2020     4
    Nan           5
    Nan           6
    Nan           7

I want to replace the Nans with a continuation of the dates. There around 100 rows in the dataset.

So I want the df to look like this.

  Date         Day_number
   10/03/2020     1
   11/03/2020     2
   12/03/2020     3
   13/03/2020     4
   14/03/2020     5
   15/03/2020     6
   16/03/2020     7
      .           .
      .           .

Any help would be greatly appreciated. Thanks in advance.

标签: pythonpandas

解决方案


IIUC

df.Date=pd.to_datetime(df.Date,errors='coerce',dayfirst=True)
s=df.Date.isnull()
df.loc[s,'Date']=pd.to_timedelta(df.Day_number.diff()[s].cumsum(),unit='day')+df['Date'].ffill()
df
        Date  Day_number
0 2020-03-10           1
1 2020-03-11           2
2 2020-03-12           3
3 2020-03-13           4
4 2020-03-14           5
5 2020-03-15           6
6 2020-03-16           7

推荐阅读