สมมติว่าคุณมี DataFrame ที่มี DatetimeIndex และต้องการเลื่อน (shift) index ไปข้างหน้าและข้างหลัง 2 ช่วง
วิธีแก้ปัญหา
- สร้าง time series ด้วย
pd.date_range()start='01-01-2020', periods=5, freq='12H' - สร้าง DataFrame ใช้ time series เป็น index
- ใช้
df.shift(2, axis=0)เลื่อนลง 2 แถว (ทิศทางบวก) - ใช้
df.shift(-2, axis=0)เลื่อนขึ้น 2 แถว (ทิศทางลบ)
ตัวอย่างโค้ด
import pandas as pd
# สร้าง time series: 5 จุด ทุก 12 ชั่วโมง
time_series = pd.date_range('01-01-2020', periods=5, freq='12H')
df = pd.DataFrame({"Id": [1, 2, 3, 4, 5], "Age": [10, 12, 14, 11, 13]}, index=time_series)
print("DataFrame ต้นฉบับ:\n", df)
print("\nเลื่อน index 2 ช่วงทิศทางบวก (shift down):")
print(df.shift(2, axis=0))
print("\nเลื่อน index 2 ช่วงทิศทางลบ (shift up):")
print(df.shift(-2, axis=0))
ผลลัพธ์
DataFrame ต้นฉบับ:
Id Age
2020-01-01 00:00:00 1 10
2020-01-01 12:00:00 2 12
2020-01-02 00:00:00 3 14
2020-01-02 12:00:00 4 11
2020-01-03 00:00:00 5 13
เลื่อน index 2 ช่วงทิศทางบวก (shift down):
Id Age
2020-01-01 00:00:00 NaN NaN
2020-01-01 12:00:00 NaN NaN
2020-01-02 00:00:00 1.0 10.0
2020-01-02 12:00:00 2.0 12.0
2020-01-03 00:00:00 3.0 14.0
เลื่อน index 2 ช่วงทิศทางลบ (shift up):
Id Age
2020-01-01 00:00:00 3.0 14.0
2020-01-01 12:00:00 4.0 11.0
2020-01-02 00:00:00 5.0 13.0
2020-01-02 12:00:00 NaN NaN
2020-01-03 00:00:00 NaN NaN
คำอธิบาย:
shift(2, axis=0): เลื่อนข้อมูลลง 2 แถว index คงที่ ค่าที่เลื่อนออกไปจะกลายเป็น NaNshift(-2, axis=0): เลื่อนข้อมูลขึ้น 2 แถว- ใช้สำหรับ time series analysis เช่น คำนวณการเปลี่ยนแปลงระหว่างช่วงเวลา (lag/lead)