user7162063
user7162063

Reputation: 23

Pandas, how to reorder by date

I have a Pandas dataframe that has two columns and looks like:

    title      date
   Event0     2016-01-03
   Event1     2016-02-28
   Event2     2016-06-19
   Event3     2016-04-17
   Event4     2015-11-12

etc...

I would like to reorder the events by date in descending order by date and then create a python dictionary of the results. Thus, I'd like my python dictionary's key(string),value(datetime) pair to look like:

result_dictionary = { 
    'Event2': 2016-06-19, 
    'Event3': 2016-04-17, 
    'Event1': 2016-02-28,  
    'Event0': 2016-01-03,  
    'Event4': 2015-11-12
}

What is the most efficient way to do this?

Thank-you

Upvotes: 2

Views: 154

Answers (2)

jezrael
jezrael

Reputation: 862781

You need OrderedDict, because you cannot sort a dict because dictionary has no ordering:

from collections import OrderedDict

d = df.set_index('title').date.to_dict()
print (d)
{'Event1': '2016-02-28', 
 'Event4': '2015-11-12', 
 'Event0': '2016-01-03', 
 'Event3': '2016-04-17', 
 'Event2': '2016-06-19'}


od = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))
print (od)
OrderedDict([('Event2', '2016-06-19'), 
             ('Event3', '2016-04-17'), 
             ('Event1', '2016-02-28'), 
             ('Event0', '2016-01-03'), 
             ('Event4', '2015-11-12')])

d = df.set_index('title').date.sort_values(ascending=False).to_dict()
print (d)
{'Event0': '2016-01-03', 
 'Event4': '2015-11-12', 
 'Event1': '2016-02-28',
 'Event3': '2016-04-17',
 'Event2': '2016-06-19'}

Upvotes: 3

ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19375

try this

dataframe.sort_values(by = 'date', ascending = False, inplace = True)
dataframe.to_dict()

docs here http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html

Upvotes: 1

Related Questions