微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 按第一个值对组进行排序,而不更改组顺序

我试图在不改变块内顺序的情况下逐块排序pandas数据帧.

数据框包含论坛帖子,时间戳和线程名称.我已经对数据框进行了排序,使得df.sort_values([‘thread’,’timestamp’],inplace = True)属于同一个线程的所有帖子都是正确的顺序.我现在想要根据每个块中第一个帖子的时间戳对属于同一线程的数据块进行排序.块内的顺序应保持不变.

我目前拥有的:

    post   timestamp         thread
0   this   2009/10/30 16:51  hello   
1   be     2009/11/02 17:11  hello
2   some   2008/07/10 15:23  nice
3   text   2007/04/22 14:11  question
4   this   2007/04/24 11:03  question
5   be     2007/05/03 17:55  question
6   some   2004/09/01 09:32  game
7   text   2010/01/01 03:32  wheather

我想要的是:

    post   timestamp         thread
6   some   2004/09/01 09:32  game
3   text   2007/04/22 14:11  question
4   this   2007/04/24 11:03  question
5   be     2007/05/03 17:55  question
2   some   2008/07/10 15:23  nice
0   this   2009/10/30 16:51  hello   
1   be     2009/11/02 17:11  hello
7   text   2010/01/01 03:32  wheather

有没有办法做到这一点?

解决方法:

让我们首先尝试groupby线程,然后获取第一条记录,按时间对这些记录进行排序,然后使用DataFrameGroupBy的groups属性获取每个组中当前的索引顺序.最后,使用pd.concat和list comprehension以第一条记录的排序顺序重建数据帧.

g = df.groupby('thread')
s = g.head(1).sort_values('timestamp')['thread']
dg = g.groups

pd.concat([df.reindex(dg[i[1]]) for i in s.iteritems()])

输出

   post           timestamp    thread
6  some 2004-09-01 09:32:00      game
3  text 2007-04-22 14:11:00  question
4  this 2007-04-24 11:03:00  question
5    be 2007-05-03 17:55:00  question
2  some 2008-07-10 15:23:00      nice
0  this 2009-10-30 16:51:00     hello
1    be 2009-11-02 17:11:00     hello
7  text 2010-01-01 03:32:00  wheather

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐