用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

猜你喜欢