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

Python Pandas - Lấy tuần trong năm từ Period object

Để lấy tuần trong năm từ Period object, sử dụng thuộc tính period.weekofyear (hoặc period.week trong phiên bản mới).

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

1. Import thư viện

import pandas as pd

2. Tạo hai Period object

period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)

3. Lấy tuần trong năm

res1 = period1.weekofyear
res2 = period2.weekofyear

Ví dụ hoàn chỉnh

import pandas as pd

period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)

print("Period1...\n", period1)
print("Period2...\n", period2)

res1 = period1.weekofyear
res2 = period2.weekofyear

print("\nTuần trong năm từ Period1...\n", res1)
print("\nTuần trong năm từ Period2...\n", res2)

Kết quả đầu ra

Period1...
2020-09-23
Period2...
2021-04-16
Tuần trong năm từ Period1...
39
Tuần trong năm từ Period2...
15

Giải thích:

  • 23/9/2020 thuộc tuần 39 (theo quy ước ISO/US: tuần đầu năm là tuần chứa 1/1)
  • 16/4/2021 thuộc tuần 15

Lưu ý phiên bản Pandas:

  • Pandas < 1.1.0: dùng weekofyear
  • Pandas ≥ 1.1.0: weekofyear deprecated, dùng week (tuân thủ ISO week)
  • ISO week: tuần đầu năm là tuần chứa thứ 4 đầu tiên, bắt đầu thứ 2
# Pandas mới
period.week          # ISO week (1-53)
period.weekofyear    # Deprecated warning