BeautifulBlood
BeautifulBlood

Reputation: 3

How to sort dates imported from a CSV file?

I'm trying to write a program that can print a list of sorted dates but it keeps sorting by the 'day' instead of the full date, day,month,year

Im very new to python so theres probably a lot i'm doing wrong but any help would be greatly appreciated. So I have it so that you can view the list over two pages. the dates will sort 12/03/2004 13/08/2001 15/10/2014 but I need the full date sorted

df = pd.read_csv('Employee.csv')
df = df.sort_values('Date of Employment.')
List1 = df.iloc[:50, 1:]
List2 = df.iloc[50:99, 1:]

Upvotes: 0

Views: 949

Answers (2)

ansev
ansev

Reputation: 30920

The datetime data type has to be used for the dates to be sorted correctly

You need to use either one of these approaches to convert the dates to datetime objects:

Approach 1

pd.to_datetime + DataFrame.sort_values:

df['Date of Employment.'] = pd.to_datetime(df['Date of Employment.']')

Approach 2

You can parse the dates at the same time that the Pandas DataFrame is being loaded:

df = pd.read_csv('Employee.csv', parse_dates=['Date of Employement.'])

This is equivalent to the first approach with the exception that everything is done in one step.


Next you need to sort the datetime values in either ascending or descending order.

Ascending:

`df.sort_values('Date of Employment.')`

Descending

`df.sort_values('Date of Employment.',ascending=False)`

Upvotes: 1

fmarm
fmarm

Reputation: 4284

You need to convert Date of Employment. to a Date before sorting

df['Date of Employment.'] = pd.to_datetime(df['Date of Employment.'],format= '%d/%m/%Y')

Otherwise it's just strings for Python

Upvotes: 0

Related Questions