如何在python中按升序将NAT中的缺失日期替换为某个日期

时间:2019-03-19 09:04:43

标签: python python-3.x

我有一个日期列

enter image description here

缺少的值(python中的NAT)需要在一天之内循环增加 那是1/1/2015,1/2/2016,1/3/2016

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这将为您的数据框添加一个增量日期。

import pandas as pd
import datetime as dt

ddict = {
    'Date': ['2014-12-29','2014-12-30','2014-12-31','','','','',]
    }

data = pd.DataFrame(ddict)
data['Date'] = pd.to_datetime(data['Date'])

def fill_dates(data_frame, date_col='Date'):
    ### Seconds in a day (3600 seconds per hour x 24 hours per day)
    day_s = 3600 * 24

    ### Create datetime variable for adding 1 day
    _day = dt.timedelta(seconds=day_s)

    ### Get the max non-null date
    max_dt = data_frame[date_col].max()

    ### Get index of missing date values
    NaT_index = data_frame[data_frame[date_col].isnull()].index

    ### Loop through index; Set incremental date value; Increment variable by 1 day
    for i in NaT_index:
        data_frame[date_col][i] = max_dt + _day
        _day += dt.timedelta(seconds=day_s)

### Execute function
fill_dates(data, 'Date')

初始数据帧:

        Date
0 2014-12-29
1 2014-12-30
2 2014-12-31
3        NaT
4        NaT
5        NaT
6        NaT

运行该功能后:

        Date
0 2014-12-29
1 2014-12-30
2 2014-12-31
3 2015-01-01
4 2015-01-02
5 2015-01-03
6 2015-01-04