0

I have a dataframe that looks like the following

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

and I would like to add the missing day and fill the values for A and B with 0 so I get

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

How is this achieved best?

1 Answer 1

2

If Date is column create DatetimeIndex and then use 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

If first column is 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.