編寫一個Python程式,列印給定時間序列資料中的前三天和後三天。


假設您有時間序列資料,並且需要得到給定序列中前三天和後三天的結果,如下所示:

first three days:
2020-01-01    Chennai
2020-01-03    Delhi
Freq: 2D, dtype: object
last three days:
2020-01-07    Pune
2020-01-09    Kolkata
Freq: 2D, dtype: object

為了解決這個問題,我們將遵循以下步驟:

解決方案

  • 定義一個序列並將其儲存為資料。

  • 在起始日期為“2020-01-01”,週期為5,頻率為“2D”的情況下,應用pd.date_range()函式,並將其儲存為time_series。

time_series = pd.date_range('2020-01-01', periods = 5, freq ='2D')
  • 設定date.index = time_series。

  • 使用data.first(’3D’)列印前三天,並將其儲存為first_day。

first_day = data.first('3D')
  • 使用data.last(’3D’)列印後三天,並將其儲存為last_day。

last_day = data.last('3D')

示例

讓我們檢查以下程式碼以更好地理解:

import pandas as pd
data = pd.Series(['Chennai', 'Delhi', 'Mumbai', 'Pune', 'Kolkata'])
time_series = pd.date_range('2020-01-01', periods = 5, freq ='2D')
data.index = time_series
print("time series:\n",data)
first_day = data.first('3D')
print("first three days:\n",first_day)
last_day = data.last('3D')
print("last three days:\n",last_day)

輸出

time series:
2020-01-01    Chennai
2020-01-03    Delhi
2020-01-05    Mumbai
2020-01-07    Pune
2020-01-09    Kolkata
Freq: 2D, dtype: object
first three days:
2020-01-01    Chennai
2020-01-03    Delhi
Freq: 2D, dtype: object
last three days:
2020-01-07    Pune
2020-01-09    Kolkata
Freq: 2D, dtype: object

更新於:2021年2月25日

127 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.