當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas DatetimeIndex.snap()用法及代碼示例

Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。

Pandas DatetimeIndex.snap()函數用於將時間戳捕捉到最近發生的頻率。該函數采用一個參數,即我們在捕捉DatetimeIndex對象的時間戳值時要應用的頻率。

用法: DatetimeIndex.snap(freq)

參數:
freq:頻率

返回:日期時間索引

範例1:采用DatetimeIndex.snap()函數根據輸入頻率將給定的DatetimeIndex對象轉換為最近的發生頻率。

# importing pandas as pd 
import pandas as pd 
  
# Create the DatetimeIndex 
# Here 'Q' represents quarter end frequency  
didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q', 
                          periods = 4, tz ='Asia/Calcutta') 
  
# Print the DatetimeIndex 
print(didx)

輸出:

現在,我們要基於輸入將給定的DatetimeIndex對象時間戳值轉換為最接近的頻率。

# snap the timestamp to the nearest frequency  
didx.snap('MS')

輸出:

從輸出中可以看到,該函數已將給定的DatetimeIndex對象中的每個時間戳值對齊。

範例2:采用DatetimeIndex.snap()函數根據輸入頻率將給定的DatetimeIndex對象轉換為最近的發生頻率。

# importing pandas as pd 
import pandas as pd 
  
# Create the DatetimeIndex 
# Here 'MS' represents month start frequency  
didx = pd.date_range(pd.Timestamp("2000-01-15 08:00"),  
                              periods = 5, freq ='MS') 
  
# Print the DatetimeIndex 
print(didx)

輸出:

現在,我們要基於輸入將給定的DatetimeIndex對象時間戳值轉換為最接近的頻率。

# snap the timestamp to the nearest frequency  
didx.snap('Q')

輸出:

從輸出中可以看到,該函數已將給定的DatetimeIndex對象中的每個時間戳值對齊。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas DatetimeIndex.snap()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。