编写一个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.