Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Trích xuất số tháng từ DateTimeIndex

Để trích xuất số tháng (1-12) từ DateTimeIndex, sử dụng thuộc tính DateTimeIndex.month.

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex (tần suất tháng)

datetimeindex = pd.date_range(
    '2021-09-24 02:35:55',
    periods=6,
    tz='Australia/Sydney',
    freq='M'
)

3. Hiển thị DateTimeIndex

print("DateTimeIndex...\n", datetimeindex)

4. Trích xuất số tháng

print("\nSố tháng (1-12)...\n", datetimeindex.month)

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range(
    '2021-09-24 02:35:55',
    periods=6,
    tz='Australia/Sydney',
    freq='M'
)

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nSố tháng (1-12)...\n", datetimeindex.month)

Kết quả đầu ra

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...


Số tháng (1-12)...
Int64Index([9, 10, 11, 12, 1, 2], dtype='int64')

Giải thích

  • freq='M' = Month End (cuối tháng)
  • Kết quả: 9 (Tháng 9), 10, 11, 12, 1 (Tháng 1 năm sau), 2
  • Thuộc tính .month trả về số tháng 1-12, không quan tâm năm

Các thuộc tính liên quan

  • .month_name(): Tên tháng tiếng Anh ('September', 'October'...)
  • .quarter: Quý (1-4)
  • .days_in_month: Số ngày trong tháng đó (28-31)
  • .is_month_start / .is_month_end: Boolean có phải đầu/cuối tháng

Ứng dụng: Groupby theo tháng, phân tích mùa vụ, lọc dữ liệu theo tháng.