从特定时间序列频率的DateTimeIndex中提取小时Python Pandas
要从特定时间序列频率的DateTimeIndex中提取小时,请使用 DateTimeIndex.hour 属性。
首先,导入所需的库−
import pandas as pd
带有周期6和频率为H即小时的DatetimeIndex。时区为Australia/Sydney−
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='H')
显示DateTimeIndex−
print("DateTimeIndex...\n", datetimeindex)
获取小时−
print("\nGetting the hour..\n",datetimeindex.hour)
例子
以下是代码-
import pandas as pd
# 带有周期6和频率为H即小时的DatetimeIndex
# 时区为Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='H')
# 显示DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# 显示DateTimeIndex频率
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# 获取小时
print("\nGetting the hour..\n",datetimeindex.hour)
输出
这将产生以下代码−
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-20 03:35:55+11:00',
'2021-10-20 04:35:55+11:00', '2021-10-20 05:35:55+11:00',
'2021-10-20 06:35:55+11:00', '2021-10-20 07:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='H')
DateTimeIndex frequency...
<Hour>
Getting the hour..
Int64Index([2, 3, 4, 5, 6, 7], dtype='int64')