Python Pandas – 从DateTimeIndex中提取每年的序数日(ordinal day)并设置特定的时间序列频率
要从DatetimeIndex中提取符合特定时间序列频率条件下的每年的序数日,可以使用 DateTimeIndex.dayofyear 属性。
首先,导入必要的库 −
import pandas as pd
创建一个周期为6,以 D(天)为频率的 DatetimeIndex −
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='D')
显示DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
获取每年的序数日 −
print("\n获取每年的序数日...\n",datetimeindex.dayofyear)
示例
下面是代码 −
import pandas as pd
# DatetimeIndex with period 6 and frequency as D i.e. day
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='D')
# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# get the day of year
print("\n获取每年的序数日...\n",datetimeindex.dayofyear)
输出
输出如下所示 −
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-21 02:30:50+11:00',
'2021-10-22 02:30:50+11:00', '2021-10-23 02:30:50+11:00',
'2021-10-24 02:30:50+11:00', '2021-10-25 02:30:50+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='D')
DateTimeIndex frequency...
<Day>
获取每年的序数日...
Int64Index([293, 294, 295, 296, 297, 298], dtype='int64')