Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Lấy chỉ số index giá trị tại thời điểm cụ thể trong DateTimeIndex

Để lấy chỉ số (index locations) các giá trị trong DateTimeIndex khớp chính xác một thời điểm trong ngày, dùng phương thức DateTimeIndex.indexer_at_time().

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

3. Lấy index tại thời điểm cụ thể

print("\nIndex locations tại 03:10:50:\n", datetimeindex.indexer_at_time('2021-10-30 03:10:50'))

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

print("DateTimeIndex:\n", datetimeindex)
print("\nTần suất:", datetimeindex.freq)

# Index tại 03:10:50
print("\nIndex locations tại 03:10:50:\n", datetimeindex.indexer_at_time('2021-10-30 03:10:50'))

Kết quả đầu ra

DateTimeIndex:
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 02:50:50+10:30', '2021-10-30 03:10:50+10:30', '2021-10-30 03:30:50+10:30', '2021-10-30 03:50:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T')
Tần suất: <20 * Minutes>
Index locations tại 03:10:50:
[2]

Giải thích

  • Chỉ index 2 (timestamp 03:10:50) khớp chính xác.
  • Tham số thời gian có thể là string 'HH:MM:SS' hoặc 'YYYY-MM-DD HH:MM:SS' - chỉ thành phần time được so khớp.
  • Trả về Int64Index các vị trí nguyên tử (0-based).

Ứng dụng thực tế

# Lấy dữ liệu tại giờ mở cửa 9:30 hàng ngày
market_open_idx = df.index.indexer_at_time('09:30:00')
df_open = df.iloc[market_open_idx]

# Kết hợp với between_time
morning_idx = df.index.indexer_between_time('09:30', '12:00')
df_morning = df.iloc[morning_idx]

Lưu ý

  • Chỉ hoạt động trên DateTimeIndex (không phải PeriodIndex, TimedeltaIndex).
  • Múi giờ: so khớp theo local time của index (đã convert tz).
  • Nếu không khớp nào → trả về Int64Index rỗng.