Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Convert the DateTimeIndex to Series
To convert a DateTimeIndex to Series, use the DateTimeIndex.to_series() method. This method creates a Series where both the index and values are the same datetime objects from the original DateTimeIndex.
Syntax
DateTimeIndex.to_series(index=None, name=None)
Parameters
index ? Index to use for the Series (optional). If None, uses the DateTimeIndex itself.
name ? Name for the resulting Series (optional).
Creating a DateTimeIndex
First, let's create a DateTimeIndex with 5 periods and 40-second frequency in Australia/Adelaide timezone ?
import pandas as pd
# Create DatetimeIndex with period 5 and frequency as 40 seconds
# Timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
print("DateTimeIndex...")
print(datetimeindex)
print("\nDateTimeIndex frequency...")
print(datetimeindex.freq)
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')
DateTimeIndex frequency...
<40 * Seconds>
Converting DateTimeIndex to Series
Use the to_series() method to convert the DateTimeIndex to a Series ?
import pandas as pd
# Create DatetimeIndex
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
# Convert DateTimeIndex to Series
series = datetimeindex.to_series()
print("DateTimeIndex to Series...")
print(series)
print("\nSeries type:", type(series))
print("Series dtype:", series.dtype)
DateTimeIndex to Series... 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 Freq: 40S, dtype: datetime64[ns, Australia/Adelaide] Series type: <class 'pandas.core.series.Series'> Series dtype: datetime64[ns, Australia/Adelaide]
Key Points
? The resulting Series has the same datetime values as both index and values
? The timezone and frequency information is preserved
? This is useful for time series analysis and datetime operations
Conclusion
The to_series() method converts a DateTimeIndex to a Series where datetime values serve as both index and values. This conversion preserves timezone and frequency information, making it useful for time series operations.
