- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a program in Python to print the first and last three days from a given time series data
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
Advertisements