用 Python 编写一个程序,打印给定时间序列数据中的前三天和后三天
pythonpandasserver side programmingprogramming
假设您有时间序列,并且给定序列中前三天和后三天的结果是,
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’和 periods = 5、freq =’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