Print First and Last Three Days from Time Series Data in Python



Assume, you have time series and the result for the first and last three days from the given series as,

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

To solve this, we will follow the steps given below −

Solution

  • Define a series and store it as data.

  • Apply pd.date_range() function inside start date as ‘2020-01-01’ and periods = 5, freq =’2D’ and save it as time_series

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

  • Print the first three days using data.first(’3D’) and save it as first_day

first_day = data.first('3D')
  • Print the last three days using data.last(’3D’) and save it as last_day

last_day = data.last('3D')

Example

Let’s check the following code to get a better understanding −

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)

Output

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
Updated on: 2021-02-25T06:52:25+05:30

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements