Python Pandas dataframe.shift()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。Pandas就是这些包中的一个,使导入和分析数据变得更加容易。
Pandas dataframe.shift() 函数 通过所需的周期数和可选的时间频率转移索引。这个函数需要一个标量参数,称为周期,它表示在所需的axis上进行的移位次数。这个函数在处理时间序列数据时非常有用。
语法: DataFrame.shift(periods=1, freq=None, axis=0)
参数 :
periods:移动的周期数,可以是正数或负数
freq : DateOffset, timedelta, or time rule string, optional Increment to use from the tseries module or time rule (e.g. ‘EOM’)。见注释
axis: {0或’索引’,1或’列’}
返回 : shifted :数据框架
例子#1:使用shift()函数将时间序列数据中的索引axis移动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()函数将指数axis向正方向移动2个周期
# shift index axis by two periods in positive direction
# axis = 0 is set by default
df.shift(2, axis = 0)
输出:
让我们把指数axis向负方向移动一些时期
# shift index axis by two periods in negative direction
# axis = 0 is set by default
df.shift(-2, axis = 0)
输出 :
实例2:使用shift()函数在一个时间序列数据中把列axis移动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()函数将列axis向正方向移动2个周期
# shift column axis by two periods in positive direction
df.shift(2, axis = 1)
让我们把柱axis向负方向移动一些时期
# shift column axis by two periods in negative direction
df.shift(-2, axis = 1)
输出 :