Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - ดึงไตรมาสของวันที่จาก DateTimeIndex ด้วย quarter property


คำอธิบาย

ใช้ property DateTimeIndex.quarter เพื่อดึงหมายเลขไตรมาส (1-4) ของแต่ละวันที่ใน DateTimeIndex

ไตรมาสของปี

  • Q1: 1 ม.ค. - 31 มี.ค.
  • Q2: 1 เม.ย. - 30 มิ.ย.
  • Q3: 1 ก.ค. - 30 ก.ย.
  • Q4: 1 ต.ค. - 31 ธ.ค.

ตัวอย่างโค้ด

import pandas as pd

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='2M')

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nGet the quarter of the date..\n", datetimeindex.quarter)

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-10-31 02:30:50+11:00', '2021-12-31 02:30:50+11:00',
               '2022-02-28 02:30:50+11:00', '2022-04-30 02:30:50+10:00',
               '2022-06-30 02:30:50+10:00', '2022-08-31 02:30:50+10:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='2M')

Get the quarter of the date..
Int64Index([4, 4, 1, 2, 2, 3], dtype='int64')