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

Python Pandas - ดึงสัปดาห์ของปีจากออบเจ็กต์ PeriodIndex

หากต้องการดึงสัปดาห์ของปีจากออบเจ็กต์ PeriodIndex สามารถใช้คุณสมบัติ PeriodIndex.week ได้

ขั้นตอนการทำงาน

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.week)

ตัวอย่างโค้ดสมบูรณ์

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.week)

ผลลัพธ์ที่คาดหวัง

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([38, 44, 28, 25], dtype='int64')

คำอธิบาย: ค่าที่ได้ [38, 44, 28, 25] แสดงถึง หมายเลขสัปดาห์ในปีของแต่ละวันที่ (ตามมาตรฐาน ISO week date)