用 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'和period=5,freq='2D'并将其保存为time_seriespd.date_range()
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