Để chuyển đổi DateTimeIndex thành Giai đoạn, hãy sử dụng datetimeindex.to_period () trong Pandas. Tần suất được đặt bằng tần suất tham số.
Đầu tiên, hãy nhập các thư viện được yêu cầu -
import pandas as pd
Tạo DatetimeIndex với chu kỳ 5 và tần suất là Y tức là năm -
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5, freq='2Y')
Hiển thị DateTimeIndex -
print("DateTimeIndex...\n", datetimeindex) Chuyển đổi DateTimeIndex thành Kỳ. Chúng tôi đã đặt tần suất là Tháng bằng cách sử dụng thông số "freq" với giá trị 'M' -
print("\nConvert DateTimeIndex to Period...\n",
datetimeindex.to_period(freq='M')) Ví dụ
Sau đây là mã -
import pandas as pd
# DatetimeIndex with period 5 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')) Đầu ra
Điều này sẽ tạo ra mã sau -
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]')