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

Python Pandas - Trích xuất năm từ DateTimeIndex

Để trích xuất năm từ DateTimeIndex, sử dụng thuộc tính DateTimeIndex.year.

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 năm)

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

3. Hiển thị DateTimeIndex

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

4. Trích xuất năm

print("\nNăm...\n", datetimeindex.year)

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='Y'
)

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nNăm...\n", datetimeindex.year)

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-12-31 02:35:55+11:00', '2022-12-31 02:35:55+11:00',
               '2023-12-31 02:35:55+11:00', '2024-12-31 02:35:55+11:00',
               '2025-12-31 02:35:55+11:00', '2026-12-31 02:35:55+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='A-DEC')

DateTimeIndex frequency...


Năm...
Int64Index([2021, 2022, 2023, 2024, 2025, 2026], dtype='int64')

Giải thích

  • freq='Y' = Year End (cuối năm, mặc định tháng 12)
  • Kết quả: 2021, 2022, 2023, 2024, 2025, 2026
  • freq='A-DEC' trong output xác nhận tần suất Year End tháng 12

Các tần suất năm khác

  • 'Y' / 'A': Cuối năm (tháng 12)
  • 'Y-JUN' / 'A-JUN': Cuối năm tài chính tháng 6
  • 'Y-MAR': Cuối năm tài chính tháng 3

Thuộc tính năm liên quan

  • .is_year_start / .is_year_end: Boolean đầu/cuối năm
  • .days_in_year: 365 hoặc 366 (năm nhuận)
  • .year vs .strftime('%Y'): year trả về Int64Index (số), strftime trả về Index chuỗi

Ứng dụng: Groupby theo năm, lọc dữ liệu năm tài chính, phân tích xu hướng hàng năm.