我有一个如下数据框
Date A B
2014-12-20 00:00:00.000 3 2
2014-12-21 00:00:00.000 7 1
2014-12-22 00:00:00.000 2 9
2014-12-24 00:00:00.000 2 2
我想添加缺少的日期,并用0填充A和B的值,以便得到
Date A B
2014-12-20 00:00:00.000 3 2
2014-12-21 00:00:00.000 7 1
2014-12-22 00:00:00.000 2 9
2014-12-23 00:00:00.000 0 0
2014-12-24 00:00:00.000 2 2
如何做到最好?
答案 0 :(得分:3)
如果Date
是列,则创建DatetimeIndex
,然后使用DataFrame.asfreq
:
df['Date'] = pd.to_datetime(df['Date'])
df1 = df.set_index('Date').asfreq('d', fill_value=0)
print (df1)
A B
Date
2014-12-20 3 2
2014-12-21 7 1
2014-12-22 2 9
2014-12-23 0 0
2014-12-24 2 2
如果第一列是index
:
df.index = pd.to_datetime(df.index)
df1 = df.asfreq('d', fill_value=0)
print (df1)
A B
Date
2014-12-20 3 2
2014-12-21 7 1
2014-12-22 2 9
2014-12-23 0 0
2014-12-24 2 2