Open In App

Sorting a CSV object by dates in Python

Last Updated : 25 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

CSV stands for comma-separated values. A CSV file can be opened in Google Sheets or Excel and will be formatted as a spreadsheet. However, a CSV file is actually a plain-text file. It can also be opened with a text editor program such as Atom. In this article, we are going to see how to sort a CSV object by dates in Python

CSVs give us a good, simple way to organize data without using a database program. It’s easy to read from and write to CSV files with Python.

Steps to Read a CSV file

Step 1: In the first step to read a CSV you need to find the file.

Step 2: Import pandas library 

The pandas library is exported by using import keyword and object as pd which is a standard notation for pandas library.

Python3




import pandas as pd


Step 3: Read the CSV file by using pandas library and assign it to a variable.

The csv file ‘data.csv’ is loaded by using read_csv method present in the pandas library and stored in the variable named ‘data’ and now this variable is called a dataframe.

Python3




data = pd.read_csv('data.csv')


Step 4: Display the first 5 rows of the data by using head function.

The ‘.head()’ method is used to print the first 5 rows and ‘.tail()’ method is used to print the last 5 rows of the data file.

Python3




display(data.head())


Output:

output screenshot

Steps to sort the Data by Dates

Step 1: Convert the Date column into required date time format

You can use the parameter infer_datetime_format. Example with your sample data below:

Python3




data['date'] = pd.to_datetime(data.date, infer_datetime_format = True)
display(data.head())


Output:

output screenshot

Step 2: Use the sort_values method and giving parameter as date we sort the values by date. To get the sorted while use head function to get first 5 rows of dataInput:

Python3




data.sort_values(by = 'date', ascending = True, inplace = True)
display(data.head())


Output:



Previous Article
Next Article

Similar Reads

Python - Find consecutive dates in a list of dates
Given a list of dates, the task is to write a Python program to check if all the dates are consecutive in the list. Input : [datetime(2019, 12, 30), datetime(2019, 12, 31), datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4)] Output : True Explanation : All dates are consecutive, from 30 Dec 2019 to 4 January 2020
4 min read
Python - Generate k random dates between two other dates
Given two dates, the task is to write a Python program to get K dates randomly. Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7 Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6, 11), datetime.date(2015, 6, 10), datetime.date(201
4 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Comparing dates in Python
Comparing dates is quite easy in Python. Dates can be easily compared using comparison operators (like <, >, <=, >=, != etc.). Let's see how to compare dates with the help of datetime module using Python. Code #1 : Basic C/C++ Code # Simple Python program to compare dates # importing datetime module import datetime # date in yyyy/mm/dd
4 min read
Python | Sort list of dates given as strings
Given a list of dates in string format, write a Python program to sort the list of dates in ascending order. Examples: Input : dates = ["24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997"] Output : 01 Jan 2007 10 Jul 2016 2 Dec 2017 11 Jun 2018 23 Jun 2018 01 Jan 2019 Approach: In Python, we can use sort() (for
4 min read
Python program to find number of days between two given dates
Given two dates, Write a Python program to find the total number of days between them. Examples: Input : dt1 = 13/12/2018, dt2 = 25/2/2019Output : 74 daysInput : dt1 = 01/01/2004, dt2 = 01/01/2005Output : 366 days Naive Approach: One Naive Solution is to start from dt1 and keep counting the days till dt2 is reached. This solution requires more than
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg