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

Python Pandas – เลือกช่วงแรกของ Time Series ตาม Date Offset (first)

ภาพรวม

ใช้เมธอด first() ของ DataFrame ที่มี DatetimeIndex เพื่อดึงข้อมูลช่วงแรกตาม offset (เช่น '4D' = 4 วันแรก)

ตัวอย่างโค้ด


import pandas as pd

# Date index: เริ่ม 15 ก.ค. 2021, 5 periods, ทุก 3 วัน
i = pd.date_range('2021-07-15', periods=5, freq='3D')
# Dates: 2021-07-15, 2021-07-18, 2021-07-21, 2021-07-24, 2021-07-27

dataFrame = pd.DataFrame({'k': [1, 2, 3, 4, 5]}, index=i)

print("DataFrame...\n", dataFrame)

# ดึง 4 วันแรก (offset '4D')
print("First few rows fetched..\n", dataFrame.first('4D'))

ผลลัพธ์

DataFrame...
                k
2021-07-15  1
2021-07-18  2
2021-07-21  3
2021-07-24  4
2021-07-27  5

First few rows fetched..
                k
2021-07-15  1
2021-07-18  2

คำอธิบาย

  • Index ต้องเป็น DatetimeIndex (หรือ PeriodIndex)
  • first('4D') = ข้อมูลตั้งแต่เริ่มต้นถึง 4 วัน (รวมวันที่เริ่มต้น)
  • 2021-07-15 ถึง 2021-07-18 (4 วัน) -> ได้ 2 rows
  • 2021-07-21 เป็นวันที่ 6 แล้ว -> ไม่รวม

Offset Strings

คู่คู่: last()

ใช้ last('4D') ดึงข้อมูล 4 วันสุดท้าย (ดูบทความถัดไป)

Stringความหมาย
'4D'4 วัน
'2W'2 สัปดาห์
'1M'1 เดือน (Month End)
'3H'3 ชั่วโมง
'30T' หรือ '30min'30 นาที