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

Python Pandas - ดึงปีจาก Period Object

เพื่อดึงปีจาก Period object ให้ใช้ property period.year

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

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. ดึงปีจาก Period Objects

res1 = period1.year
res2 = period2.year

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

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)

# ดึงปีจาก Period objects
res1 = period1.year
res2 = period2.year

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

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

Period1... 
2020-09-23
Period2... 
2021-04-16
Display the Year from the 1st Period object ... 
2020
Display the Year from the 2nd Period object... 
2021

คำอธิบาย: Property year คืนค่าปีเป็นจำนวนเต็ม ทำงานได้กับ Period ทุกความถี่