Python Pandas - Dataframe Sort

To sort the data coming from a .csv file, first let us read the data from the file into a data frame using read_csv() function as:

df = pd.read_csv("D:\python\PANDAS\empdata2.csv", parse_dates=['doj'])

Here, we are loading the data from empdata2.csv file and also informing to take 'doj' as date type field using parse_dates option. Now let us display the data frame as:

example image for python Sorting data

To sort the rows on 'doj' column into ascending order, we can use sort_values() method as:

example image for python Sorting the data

To sort in descending order, we should use an additional option 'ascending = False' as:

example image for python Sorting data

Sorting on multiple columns is also possible. This can be done using an option 'by ' in the sort_values() method. For example, we want to sort on 'doj' in descending order and in that 'sal' in ascending order. That means, when two employees have same 'doj', then their salaries will be sorted into ascending order.

example image for python BY Sorting data