Để trích xuất số tháng từ DateTimeIndex với tần suất chuỗi thời gian cụ thể, hãy sử dụng DateTimeIndex.month tài sản.
Đầu tiên, hãy nhập các thư viện được yêu cầu -
import pandas as pd
DatetimeIndex với chu kỳ 6 và tần suất là M tức là tháng. Múi giờ là Úc / Sydney -
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney',freq='M') Hiển thị DateTimeIndex -
print("DateTimeIndex...\n", datetimeindex) Lấy số tháng, tức là tháng 1 =1, tháng 2 =2, ..., tháng 12 =12 -
print("\nGetting the month number..\n",datetimeindex.month)
Ví dụ
Sau đây là mã -
import pandas as pd
# DatetimeIndex with period 6 and frequency as M i.e. month
# timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney',freq='M')
# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)
# get the month number i.e. January=1, february=2, ..., December=12
print("\nGetting the month number..\n",datetimeindex.month) Đầu ra
Điều này sẽ tạo ra kết quả sau -
DateTimeIndex...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
'2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
'2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='M')
DateTimeIndex frequency...
<MonthEnd>
Getting the month number..
Int64Index([9, 10, 11, 12, 1, 2], dtype='int64')