Python Pandas – 将 DateTimeIndex 转换为 Series

Python Pandas – 将 DateTimeIndex 转换为 Series

要将 DateTimeIndex 转换为 Series,请使用 DateTimeIndex.to_series() 方法。

首先,导入所需的库−

import pandas as pd

创建将要使用的 DateTimeIndex,周期为 5,频率为 S,即秒。时区为澳大利亚/阿德莱德−

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

将 DateTimeIndex 转换为 Series−

print("\nDateTimeIndex to series...\n",
datetimeindex.to_series())

示例

以下是代码−

import pandas as pd

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

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# Convert DateTimeIndex to Series
print("\nDateTimeIndex to series...\n",
datetimeindex.to_series())

输出

这将产生以下代码−

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>

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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程