Python Pandas - 在索引值与已转换至指定频率的 PeriodArray 的索引之间的差值中计算 TimedeltaArray
如需计算 TimedeltaArray,其中包含索引值与已按指定频率转换为 PeriodArray 的索引之间的差值,请使用 datetimeindex.to_perioddelta() 方法。使用 freq 参数设置频率。
请先导入所需的库 -
import pandas as pd
使用周期 7 和频率作为 Y(即年)创建日期时间索引 -
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')
显示 DateTimeIndex -
print("DateTimeIndex...\n", datetimeindex)
计算 TimedeltaArray,其中包含索引值与已转换为 PeriodArray 的索引之间的差值。我们已使用具有值“M”的“freq”参数设置 Period 频率 -
print("\nConvert DateTimeIndex to PeriodDelta...\n", datetimeindex.to_perioddelta(freq='M'))
示例
代码如下 -
import pandas as pd # DatetimeIndex with period 7 and frequency as Y i.e. year # timezone is Australia/Adelaide datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("DateTimeIndex frequency...\n", datetimeindex.freq) # Convert DateTimeIndex to Period # We have set the frequency as Month using the "freq" parameter with value 'M' print("\nConvert DateTimeIndex to Period...\n", datetimeindex.to_period(freq='M')) # Calculate TimedeltaArray of difference between index values and index converted to PeriodArray # We have set the Period frequency using the "freq" parameter with value 'M' print("\nConvert DateTimeIndex to PeriodDelta...\n", datetimeindex.to_perioddelta(freq='M'))
输出
将生成以下代码 -
DateTimeIndex... DatetimeIndex(['2021-12-31 07:20:32.261811624', '2023-12-31 07:20:32.261811624', '2025-12-31 07:20:32.261811624', '2027-12-31 07:20:32.261811624', '2029-12-31 07:20:32.261811624'], dtype='datetime64[ns]', freq='2A-DEC') DateTimeIndex frequency... <2 * YearEnds: month=12> Convert DateTimeIndex to Period... PeriodIndex(['2021-12', '2023-12', '2025-12', '2027-12', '2029-12'], dtype='period[M]') Convert DateTimeIndex to PeriodDelta... TimedeltaIndex(['30 days 07:20:32.261811624', '30 days 07:20:32.261811624', '30 days 07:20:32.261811624', '30 days 07:20:32.261811624', '30 days 07:20:32.261811624'], dtype='timedelta64[ns]', freq=None)
广告