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

Python Pandas - แปลง Period เป็นความถี่ที่ต้องการ

เพื่อแปลง Period เป็นความถี่ที่ต้องการ ให้ใช้เมธอด period.asfreq() ตัวอย่างใช้ 'H' สำหรับความถี่รายชั่วโมง

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

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

import pandas as pd

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

period1 = pd.Period("2020-09-23 03:15:40")
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.asfreq('H')
res2 = period2.asfreq('H')

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

import pandas as pd

# สร้าง Period objects 2 ตัว
period1 = pd.Period("2020-09-23 03:15:40")
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.asfreq('H')
res2 = period2.asfreq('H')

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

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

Period1... 
2020-09-23 03:15:40
Period2... 
2021-04-16
Result after conversion from the 1st Period object ... 
2020-09-23 03:00
Result after conversion from the 2nd Period object... 
2021-04-16 23:00

คำอธิบาย:

  • period1 ความถี่เดิมคือรายนาที/วินาที แปลงเป็นรายชั่วโมง ได้ 03:00 (ปัดลง)
  • period2 ความถี่เดิมคือรายวัน แปลงเป็นรายชั่วโมง ได้ 23:00 (ชั่วโมงสุดท้ายของวัน)

การแปลงจากความถี่ต่ำไปสูง (upsampling) จะสร้างช่วงย่อยได้หลายช่วง โดยค่าเริ่มต้นคือช่วงแรก หรือช่วงสุดท้าย ขึ้นอยู่กับการตั้งค่า