หากต้องการแสดงไตรมาส (Quarter) ของวันที่จากออบเจ็กต์ PeriodIndex สามารถใช้คุณสมบัติ PeriodIndex.quarter ได้
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างออบเจ็กต์ PeriodIndex
periodIndex = pd.PeriodIndex(
['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'],
freq="T"
)
3. แสดง PeriodIndex
print("PeriodIndex...\n", periodIndex)
4. ดึงไตรมาสของวันที่
print("\nไตรมาสของวันที่จาก PeriodIndex object...\n", periodIndex.quarter)
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้าง PeriodIndex object
# PeriodIndex เป็น immutable ndarray ที่เก็บค่าลำดับบ่งชี้ช่วงเวลาสม่ำเสมอ
# เราตั้งความถี่ด้วยพารามิเตอร์ "freq"
periodIndex = pd.PeriodIndex(
['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'],
freq="T"
)
# แสดง PeriodIndex object
print("PeriodIndex...\n", periodIndex)
# แสดงความถี่ของ PeriodIndex
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
# แสดงความถี่ของ PeriodIndex เป็นสตริง
print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)
# แสดงไตรมาสของวันที่จาก PeriodIndex object
print("\nไตรมาสของวันที่จาก PeriodIndex object...\n", periodIndex.quarter)
ผลลัพธ์ที่คาดหวัง
PeriodIndex... PeriodIndex(['2021-09-25 07:30', '2019-10-30 04:15', '2021-07-15 02:55', '2022-06-25 09:40'], dtype='period[T]')
PeriodIndex frequency object... <Minute>
PeriodIndex frequency object as a string... T
ไตรมาสของวันที่จาก PeriodIndex object... Int64Index([3, 4, 3, 2], dtype='int64')
คำอธิบาย: ค่าที่ได้ [3, 4, 3, 2] หมายถึง ไตรมาสที่ 3, 4, 3, 2 ตามลำดับ (1=ม.ค.-มี.ค., 2=เม.ย.-มิ.ย., 3=ก.ค.-ก.ย., 4=ต.ค.-ธ.ค.)