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


Python Pandas Series.tshift()用法及代碼示例

Pandas 係列是帶有軸標簽的一維ndarray。標簽不必是唯一的,但必須是可哈希的類型。該對象同時支持基於整數和基於標簽的索引,並提供了許多方法來執行涉及索引的操作。

Pandas Series.tshift()函數用於移動時間索引,並使用時標的頻率(如果有)。如果未指定freq,則它將嘗試使用索引的freq或inferred_freq屬性。如果這些屬性都不存在,則會引發ValueError。

用法: Series.tshift(periods=1, freq=None, axis=0)

參數:
periods:移動的周期數,可以是正數或負數
freq:從tseries模塊或時間規則中使用的增量(例如“ EOM”)
axis:對應於包含索引的軸

返回:移動:NDFrame

範例1:采用Series.tshift()函數將給定係列對象的基於Datetime的索引移動一定的時間。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) 
  
# Create the Datetime Index 
didx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',  
                     periods = 6, tz = 'Europe/Berlin')  
  
# set the index 
sr.index = didx 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.tshift()函數將索引按係列對象已應用的頻率移動2個周期。

# shift by 2 periods 
sr.tshift(periods = 2)

輸出:


正如我們在輸出中看到的,Series.tshift()函數已成功將給定係列的基於DateTime的索引移動了2個周期。

範例2:采用Series.tshift()函數可將給定係列對象的基於DateTime的索引增加一定的時間,並在其上應用“每日”頻率。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) 
  
# Create the Datetime Index 
didx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',  
                     periods = 6, tz = 'Europe/Berlin')  
  
# set the index 
sr.index = didx 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.tshift()該函數可將序列對象已應用頻率上的索引增加4個周期。

# increment by 4 periods 
sr.tshift(periods = 4, freq = 'D')

輸出:

正如我們在輸出中看到的,Series.tshift()函數已成功將給定係列的基於DateTime的索引增加了4個周期。



相關用法


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