สมมติว่าคุณมีอนุกรมเวลา และผลลัพธ์ของวันแรกและวันสุดท้าย 3 วันจาก Series ที่กำหนดมีดังนี้:
first three days: 2020-01-01 Chennai 2020-01-03 Delhi Freq: 2D, dtype: object last three days: 2020-01-07 Pune 2020-01-09 Kolkata Freq: 2D, dtype: object
ในการแก้ปัญหานี้ เราจะทำตามขั้นตอนดังนี้:
วิธีแก้ปัญหา
กำหนด Series และเก็บไว้ในตัวแปร data
ใช้ฟังก์ชัน pd.date_range() ภายใน start date เป็น '2020-01-01' และ periods=5, freq='2D' แล้วเก็บไว้ใน time_series
time_series = pd.date_range('2020-01-01', periods=5, freq='2D')
กำหนด data.index = time_series
พิมพ์วันแรก 3 วันโดยใช้ data.first('3D') และเก็บไว้ใน first_day
first_day = data.first('3D')
พิมพ์วันสุดท้าย 3 วันโดยใช้ data.last('3D') และเก็บไว้ใน last_day
last_day = data.last('3D')
ตัวอย่าง
ลองดูโค้ดต่อไปนี้เพื่อเข้าใจได้ดียิ่งขึ้น:
import pandas as pd
data = pd.Series(['Chennai', 'Delhi', 'Mumbai', 'Pune', 'Kolkata'])
time_series = pd.date_range('2020-01-01', periods=5, freq='2D')
data.index = time_series
print("time series:\n", data)
first_day = data.first('3D')
print("first three days:\n", first_day)
last_day = data.last('3D')
print("last three days:\n", last_day)
ผลลัพธ์
time series: 2020-01-01 Chennai 2020-01-03 Delhi 2020-01-05 Mumbai 2020-01-07 Pune 2020-01-09 Kolkata Freq: 2D, dtype: object first three days: 2020-01-01 Chennai 2020-01-03 Delhi Freq: 2D, dtype: object last three days: 2020-01-07 Pune 2020-01-09 Kolkata Freq: 2D, dtype: object