用Python编写程序以将数据帧索引在正负两个方向上移动两个周期
假设您有一个数据框,并且在正负两个方向上的移位指数为两个周期,
shift the index by three periods in positive direction
Id Age
2020-01-01 00:00:00 NaN NaN
2020-01-01 12:00:00 NaN NaN
2020-01-02 00:00:00 1.0 10.0
2020-01-02 12:00:00 2.0 12.0
2020-01-03 00:00:00 3.0 14.0
shift the index by three periods in negative direction
Id Age
2020-01-01 00:00:00 3.0 14.0
2020-01-01 12:00:00 4.0 11.0
2020-01-02 00:00:00 5.0 13.0
2020-01-02 12:00:00 NaN NaN
2020-01-03 00:00:00 NaN NaN解决方案
为了解决这个问题,我们将遵循以下步骤-
使用开始='01-01-2020',周期=5,频率='12H'创建熊猫时间序列
定义一个数据框
应用,以使索引在正方向上移动两个周期,例如,df.shift()
df.shift(2,axis=0)
应用,以使索引在负方向上移动两个周期,例如,df.shift()
df.shift(-2,axis=0)
例子
让我们看下面的代码以获得更好的理解-
import pandas as pd
time_series = pd.date_range('01-01-2020', periods = 5, freq ='12H')
df = pd.DataFrame({"Id":[1, 2, 3, 4, 5],
"Age":[10, 12, 14, 11, 13]},
index = time_series)
print("Dataframe is:\n",df)
print("shift the index by three periods in positive direction")
print(df.shift(2,axis=0))
print("shift the index by three periods in negative direction")
print(df.shift(-2,axis=0))输出
Dataframe is:
Id Age
2020-01-01 00:00:00 1 10
2020-01-01 12:00:00 2 12
2020-01-02 00:00:00 3 14
2020-01-02 12:00:00 4 11
2020-01-03 00:00:00 5 13
shift the index by three periods in positive direction
Id Age
2020-01-01 00:00:00 NaN NaN
2020-01-01 12:00:00 NaN NaN
2020-01-02 00:00:00 1.0 10.0
2020-01-02 12:00:00 2.0 12.0
2020-01-03 00:00:00 3.0 14.0
shift the index by three periods in negative direction
Id Age
2020-01-01 00:00:00 3.0 14.0
2020-01-01 12:00:00 4.0 11.0
2020-01-02 00:00:00 5.0 13.0
2020-01-02 12:00:00 NaN NaN
2020-01-03 00:00:00 NaN NaN热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短