
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Truncate DataFrame Time Series Data Based on Index Value
Assume you have a dataframe with time series data and the result for truncated data is,
before truncate: Id time_series 0 1 2020-01-05 1 2 2020-01-12 2 3 2020-01-19 3 4 2020-01-26 4 5 2020-02-02 5 6 2020-02-09 6 7 2020-02-16 7 8 2020-02-23 8 9 2020-03-01 9 10 2020-03-08 after truncate: Id time_series 1 2 2020-01-12
Solution
To solve this, we will follow the steps given below −
Define a dataframe.
Create date_range function inside start=’01/01/2020’, periods = 10 and assign freq = ‘W’. It will generate ten dates from given start date to next weekly start dates and store it as df[‘time_series’].
df['time_series'] = pd.date_range('01/01/2020', periods=10, freq='W')
Apply df.truncate() function inside some index values as before=’01/01/2020’, after=’10/02/2020’ and store it as result,
result = df.truncate(before='01/01/2020',after='10/02/2020')
Example
Let’s see the below implementation to get a better understanding −
import pandas as pd d = {'Id': [1,2,3,4,5,6,7,8,9,10]} df = pd.DataFrame(d) df['time_series'] = pd.date_range('01/01/2020', periods=10, freq='W') print(df) result = df.truncate(before='01/01/2020',after='10/02/2020') print(result)
Output
before truncate: Id time_series 0 1 2020-01-05 1 2 2020-01-12 2 3 2020-01-19 3 4 2020-01-26 4 5 2020-02-02 5 6 2020-02-09 6 7 2020-02-16 7 8 2020-02-23 8 9 2020-03-01 9 10 2020-03-08 after truncate: Id time_series 1 2 2020-01-12
Advertisements