Python Pandas - Create a DataFrame from DateTimeIndex but override the name of the resulting column

To create a DataFrame from a DateTimeIndex, use the datetimeindex.to_frame() method. The name parameter allows you to override the column name in the resulting DataFrame.

Creating a DateTimeIndex

First, let's create a DateTimeIndex with timezone information ?

import pandas as pd

# Create a DateTimeIndex with period 5, frequency 40 seconds, and timezone
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
                             tz='Australia/Adelaide', freq='40S')

print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
               '2021-10-18 07:21:12.261811624+10:30',
               '2021-10-18 07:21:52.261811624+10:30',
               '2021-10-18 07:22:32.261811624+10:30',
               '2021-10-18 07:23:12.261811624+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='40S')

Converting to DataFrame with Custom Column Name

Use to_frame() with the name parameter to specify a custom column name ?

import pandas as pd

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
                             tz='Australia/Adelaide', freq='40S')

# Convert to DataFrame with custom column name
df = datetimeindex.to_frame(name='DateTimeData')
print(df)
                       DateTimeData
2021-10-18 07:20:32.261811624+10:30 2021-10-18 07:20:32.261811624+10:30
2021-10-18 07:21:12.261811624+10:30 2021-10-18 07:21:12.261811624+10:30
2021-10-18 07:21:52.261811624+10:30 2021-10-18 07:21:52.261811624+10:30
2021-10-18 07:22:32.261811624+10:30 2021-10-18 07:22:32.261811624+10:30
2021-10-18 07:23:12.261811624+10:30 2021-10-18 07:23:12.261811624+10:30

Removing Index with Custom Column Name

Set index=False to prevent the DateTimeIndex from becoming the DataFrame index ?

import pandas as pd

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
                             tz='Australia/Adelaide', freq='40S')

# Convert to DataFrame without using DateTimeIndex as index
df = datetimeindex.to_frame(index=False, name='DateTimeData')
print(df)
                       DateTimeData
0 2021-10-18 07:20:32.261811624+10:30
1 2021-10-18 07:21:12.261811624+10:30
2 2021-10-18 07:21:52.261811624+10:30
3 2021-10-18 07:22:32.261811624+10:30
4 2021-10-18 07:23:12.261811624+10:30

Parameters

Parameter Description Default
index Whether to use DateTimeIndex as DataFrame index True
name Custom name for the resulting column None

Conclusion

Use to_frame(name='custom_name') to create a DataFrame with a custom column name. Set index=False to use a default integer index instead of the DateTimeIndex.

Updated on: 2026-03-26T17:35:32+05:30

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements