Python Pandas - 將 DateTimeIndex 中的時間戳捕捉到最近發生的頻率\n\n
若要將 DateTimeIndex 中的時間戳捕捉到最近發生的頻率,請使用 DateTimeIndex.snap() 方法。使用 freq 引數設定頻率。
首先,匯入所需的庫 −
import pandas as pd
使用週期 6 和頻率為 D(即天)建立一個 DatetimeIndex −
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
顯示 DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)捕捉時間戳到最近發生的頻率(此處為月末) −
print("\nSnap time stamps to nearest occurring frequency...\n",
datetimeindex.snap(freq='M'))示例
以下是程式碼 −
import pandas as pd
# DatetimeIndex with period 6 and frequency as D i.e. day
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# Snap time stamps to nearest occurring i.e. Month end here
print("\nSnap time stamps to nearest occurring frequency...\n",
datetimeindex.snap(freq='M'))輸出
這將生成以下程式碼 −
DateTimeIndex... DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30', '2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30', '2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='D') DateTimeIndex frequency... <Day> Snap time stamps to nearest occurring frequency... DatetimeIndex(['2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP