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

Python Pandas - หาสัปดาห์ของปีจาก Period Object

เพื่อหาสัปดาห์ของปีจาก Period object ให้ใช้ property period.weekofyear

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

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้าง Period Objects 2 ตัว

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

3. แสดง Period Objects

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

4. หาสัปดาห์ของปี

res1 = period1.weekofyear
res2 = period2.weekofyear

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

import pandas as pd

# สร้าง Period objects 2 ตัว
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)

# แสดง Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# หาสัปดาห์ของปี
res1 = period1.weekofyear
res2 = period2.weekofyear

# แสดงผลลัพธ์
print("\nWeek of the year from the 1st Period object ...\n", res1)
print("\nWeek of the year from the 2nd Period object...\n", res2)

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

Period1... 
2020-09-23
Period2... 
2021-04-16
Week of the year from the 1st Period object ... 
39
Week of the year from the 2nd Period object... 
15

คำอธิบาย: Property weekofyear คืนค่าลำดับสัปดาห์ในปี (1-52/53) ตามมาตรฐาน ISO week date