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

Python Pandas - Lấy quý (quarter) trong năm từ đối tượng Period

Để lấy thành phần quý (quarter) trong năm của đối tượng Period, sử dụng thuộc tính period.quarter.

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-02-27 08:32:48")
    • period2 = pd.Period(freq="M", year=2021, month=8, day=16, hour=2, minute=35) (tần suất tháng)
  3. Truy cập period1.quarter và period2.quarter.

Quy ước quý trong năm

  • Quý 1: 1/1 – 31/3
  • Quý 2: 1/4 – 30/6
  • Quý 3: 1/7 – 30/9
  • Quý 4: 1/10 – 31/12

Ví dụ hoàn chỉnh

import pandas as pd

period1 = pd.Period("2020-02-27 08:32:48")
period2 = pd.Period(freq="M", year=2021, month=8, day=16, hour=2, minute=35)

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

res1 = period1.quarter
res2 = period2.quarter

print("\nQuarter from the 1st Period object ...\n", res1)  # 1 (tháng 2)
print("\nQuarter from the 2nd Period object...\n", res2)   # 3 (tháng 8)

Kết quả

Period1... 2020-02-27 08:32:48
Period2... 2021-08
Quarter from the 1st Period object ... 1
Quarter from the 2nd Period object... 3