用 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 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告