用 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

解决方案

为了解决这个问题,我们将按照以下步骤操作:

  • 创建 Pandas 时间序列,起始时间为 '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

更新于: 2021-02-25

144 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告