要将PeriodIndex对象转换为Timestamp,请使用该方法。PeriodIndex.to_timestamp()
首先,导入所需的库-
import pandas as pd创建一个PeriodIndex对象-
periodIndex = pd.PeriodIndex([2021-09-25 07:30:35, 2019-10-30 04:15:45, 2020-07-15 02:55:15, 2022-06-25 09:40:55], freq="Y")显示PeriodIndex对象-
print("PeriodIndex...\n", periodIndex)将PeriodIndex转换为时间戳-
print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp())以下是代码-
import pandas as pd #CreateaPeriodIndexobject #PeriodIndexisanimmutablendarrayholdingordinalvaluesindicatingregularperiodsintime # We have set the frequency using the "freq" parameter periodIndex = pd.PeriodIndex([2021-09-25 07:30:35, 2019-10-30 04:15:45, 2020-07-15 02:55:15, 2022-06-25 09:40:55], freq="Y") #DisplayPeriodIndexobject print("PeriodIndex...\n", periodIndex) #DisplayPeriodIndexfrequency print("\nPeriodIndex frequency object...\n", periodIndex.freq) #DisplayPeriodIndexfrequency as string print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr) #ConvertPeriodIndextotimestamp print("\nPeriodIndex object to timestamp...\n", periodIndex.to_timestamp())输出结果这将产生以下代码-
PeriodIndex... PeriodIndex([2021, 2019, 2020, 2022], dtype=period[A-DEC]) PeriodIndex frequency object... <YearEnd: month=12> PeriodIndex frequency object as a string... A-DEC PeriodIndex object to timestamp... DatetimeIndex([2021-01-01, 2019-01-01, 2020-01-01, 2022-01-01], dtype=datetime64[ns], freq=None)