带有datetimeindex的Pandas数据框,按月份和年份对记录进行排序

2024-06-02 22:19:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框使用日期时间值进行索引时出现问题,我的数据框temps如下所示:

                 column      column
Index        | land_temps | ocean_temps
1861-01-01   |     -5     |    15
1861-02-01   |      0     |    17
1861-03-01   |      6     |    18
                   .
                   .
                   .
2015-11-01   |      2     |    17
2015-12-01   |     -1     |    14

总之,我有一个pandas数据框,日期作为datatimeindex,浮动(温度)作为列。 我想对这个数据帧的rekords按测量的月份进行排序,以实现如下目标:

Index        | land_temps | ocean_temps
1861-01-01   |     -5     |    15
1862-02-01   |     -4     |    13
1863-03-01   |     -6     |    14
                   .
                   .
                   .
2014-12-01   |     -2     |    13
2015-12-01   |     -1     |    14

怎么做?我试过:

temps.sort_values(by=temps.index.month, axis='index')

但我想它的工作原理不是这样的,所以有没有任何方法可以使用内置排序/GroupByPanadas方法(或类似方法)来实现这一点呢

提前感谢:)


Tags: 数据方法pandasindex排序时间column温度
1条回答
网友
1楼 · 发布于 2024-06-02 22:19:01

您可以创建两个附加列(稍后可以删除它们),然后可以根据这些列进行排序

temps['month'] = temps.index.month
temps['year'] = temps.index.year
temps.sort_values(['month', 'year']).drop(columns=['month', 'year'])

相关问题 更多 >