📜  Python|熊猫系列.shift()

📅  最后修改于: 2022-05-13 01:54:43.307000             🧑  作者: Mango

Python|熊猫系列.shift()

Pandas 系列是带有轴标签的一维 ndarray。标签不必是唯一的,但必须是可散列的类型。该对象支持基于整数和基于标签的索引,并提供了许多用于执行涉及索引的操作的方法。

Pandas Series.shift()函数将索引按所需的周期数和可选的时间频率移动。当 freq 未通过时,移动索引而不重新对齐数据。

示例 #1:使用Series.shift()函数将给定 Series 对象的数据移动 2 个句点。

# 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.shift()函数将给定系列对象中的数据移动 2 个周期。

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

输出 :

正如我们在输出中看到的, Series.shift()函数已成功地将数据转移到索引上。请注意,与最后两个索引对应的数据已被删除。

示例 #2:使用Series.shift()函数将给定 Series 对象的数据移动 -2 个句点。

# 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.shift()函数将给定系列对象中的数据移动 -2 个周期。

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

输出 :

正如我们在输出中看到的, Series.shift()函数已成功地将数据转移到索引上。请注意,前两个索引的数据已被删除。