2

How do you change a DatetimeIndex into a simple dataframe like this:

        month
0  2013-07-31
1  2013-08-31
2  2013-09-30
3  2013-10-31

This is the DatetimeIndex:

DatetimeIndex(['2013-07-31', '2013-08-31', '2013-09-30', '2013-10-31',
       '2013-11-30', '2013-12-31', '2014-01-31', '2014-02-28',
       '2014-03-31', '2014-04-30', '2014-05-31', '2014-06-30'],
        dtype='datetime64[ns]', freq='M')

Thank you.

1
  • 1
    pd.DataFrame(your_dt_index, columns=['month']) Commented Jul 17, 2018 at 4:56

2 Answers 2

3

Code below should work:

# Import libraries
import pandas as pd
import numpy as np
import datetime as dt

# Create dataframe
df = pd.DataFrame(pd.DatetimeIndex(['2013-07-31', '2013-08-31', '2013-09-30', '2013-10-31',
       '2013-11-30', '2013-12-31', '2014-01-31', '2014-02-28',
       '2014-03-31', '2014-04-30', '2014-05-31', '2014-06-30'],
        dtype='datetime64[ns]', freq='M'), columns=['month'])
df.head(2)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

Use DataFrame contructor:

idx = pd.DatetimeIndex(['2013-07-31', '2013-08-31', '2013-09-30', '2013-10-31',
       '2013-11-30', '2013-12-31', '2014-01-31', '2014-02-28',
       '2014-03-31', '2014-04-30', '2014-05-31', '2014-06-30'],
        dtype='datetime64[ns]', freq='M')

df = pd.DataFrame({'month':idx})
#alternative 
#df = pd.DataFrame({'month':df1.index})
print (df)
        month
0  2013-07-31
1  2013-08-31
2  2013-09-30
3  2013-10-31
4  2013-11-30
5  2013-12-31
6  2014-01-31
7  2014-02-28
8  2014-03-31
9  2014-04-30
10 2014-05-31
11 2014-06-30

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.