สมมติว่าคุณมี DataFrame ที่มีคอลัมน์ time series และต้องการตัด (truncate) ข้อมูลตามช่วง index ที่กำหนด
วิธีแก้ปัญหา
- สร้าง DataFrame พร้อมคอลัมน์ time series ด้วย
pd.date_range()freq='W' (รายสัปดาห์) - ใช้
df.truncate(before='01/01/2020', after='10/02/2020')ตัดข้อมูลในช่วง
ตัวอย่างโค้ด
import pandas as pd
d = {'Id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
df = pd.DataFrame(d)
# สร้าง time series 10 สัปดาห์ เริ่ม 01/01/2020
df['time_series'] = pd.date_range('01/01/2020', periods=10, freq='W')
print("ก่อน truncate:")
print(df)
# ตัดข้อมูลระหว่าง 01/01/2020 ถึง 10/02/2020
result = df.truncate(before='01/01/2020', after='10/02/2020')
print("\nหลัง truncate:")
print(result)
ผลลัพธ์
ก่อน truncate:
Id time_series
0 1 2020-01-05
1 2 2020-01-12
2 3 2020-01-19
3 4 2020-01-26
4 5 2020-02-02
5 6 2020-02-09
6 7 2020-02-16
7 8 2020-02-23
8 9 2020-03-01
9 10 2020-03-08
หลัง truncate:
Id time_series
1 2 2020-01-12
คำอธิบาย:
truncate()ตัดข้อมูลตามค่า index (ไม่ใช่ตามคอลัมน์) ต้องมี index ที่เรียงลำดับแล้วbeforeและafterรับค่า index ที่จะตัด (inclusive)- ในตัวอย่าง index เป็นค่า default (0-9) ไม่ใช่ time_series คอลัมน์ ดังนั้น truncate ทำงานกับ index ตัวเลข ไม่ใช่วันที่
- ถ้าต้องการตัดตามวันที่ ควร set time_series เป็น index ก่อน:
df.set_index('time_series').truncate(...)