gpt4 book ai didi

python - Pandas ,如何按日期重新排序

转载 作者:行者123 更新时间:2023-11-28 22:32:46 31 4
gpt4 key购买 nike

我有一个包含两列的 Pandas 数据框,如下所示:

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

等...

我想按日期按日期降序对事件重新排序,然后创建结果的 python 字典。因此,我希望我的 python 字典的键(字符串)、值(日期时间)对看起来像:

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

最有效的方法是什么?

谢谢

最佳答案

你需要OrderedDict ,因为您无法对字典进行排序,因为 dictionary 没有顺序:

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'}

关于python - Pandas ,如何按日期重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40610579/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com