当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Pandas dataframe.shift()用法及代码示例


Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。

Pandas dataframe.shift()函数根据需要的周期数移动索引,并带有可选的时间频率。该函数采用称为周期的标量参数,该参数表示要在所需轴上进行的平移次数。处理时间序列数据时,此函数非常有用。

用法:DataFrame.shift(periods=1, freq=None, axis=0)
参数:
periods: Number of periods to move, can be positive or negative
freq: DateOffset, timedelta, or time rule string, optional Increment to use from the tseries module or time rule (e.g. ‘EOM’). See Notes
axis: {0 or ‘index’, 1 or ‘columns’}

返回:shifted:DataFrame

范例1:采用shift()在时间序列数据中将索引轴移动2个周期的函数

# importing pandas as pd 
import pandas as pd 
   
# Creating row index values for our data frame 
# We have taken time frequency to be of 12 hours interval 
# We are generating five index value using "period = 5" parameter 
   
ind = pd.date_range('01 / 01 / 2000', periods = 5, freq ='12H') 
   
# Creating a dataframe with 4 columns 
# using "ind" as the index for our dataframe 
df = pd.DataFrame({"A":[1, 2, 3, 4, 5],  
                   "B":[10, 20, 30, 40, 50], 
                   "C":[11, 22, 33, 44, 55], 
                   "D":[12, 24, 51, 36, 2]},  
                    index = ind) 
  
# Print the dataframe 
df

让我们使用dataframe.shift()使索引轴向正方向移动2个周期的函数

# shift index axis by two periods in positive direction 
# axis = 0 is set by default 
df.shift(2, axis = 0)

让索引轴在负方向上移动一段时间

# shift index axis by two periods in negative direction 
# axis = 0 is set by default 
df.shift(-2, axis = 0)

输出:



范例2:采用shift()用于在时间序列数据中将列轴移动2个周期

# importing pandas as pd 
import pandas as pd 
   
# Creating row index values for our data frame 
# We have taken time frequency to be of 12 hours interval 
# We are generating five index value using "period = 5" parameter 
   
ind = pd.date_range('01 / 01 / 2000', periods = 5, freq ='12H') 
   
# Creating a dataframe with 4 columns 
# using "ind" as the index for our dataframe 
df = pd.DataFrame({"A":[1, 2, 3, 4, 5],  
                   "B":[10, 20, 30, 40, 50],  
                   "C":[11, 22, 33, 44, 55],  
                   "D":[12, 24, 51, 36, 2]},  
                    index = ind) 
  
# Print the dataframe 
df

让我们使用dataframe.shift()沿正方向将列轴移动2个周期的函数

# shift column axis by two periods in positive direction 
df.shift(2, axis = 1)

让列轴在负方向上移动一段时间

# shift column axis by two periods in negative direction 
df.shift(-2, axis = 0)

输出:



相关用法


注:本文由纯净天空筛选整理自Shubham__Ranjan大神的英文原创作品 Python | Pandas dataframe.shift()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。