简体   繁体   English

Pandas dataframe 带日期时间索引,按月和年排序记录

[英]Pandas dataframe with datetimeindex, sorting records by month and then year

I have a problem with pandas dataframe indexed with datetime values, my dataframe temps looks like this:我对使用日期时间值索引的pandas dataframe 有问题,我的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

So to sum up, I have a pandas dataframe with date as datatimeindexes, and floats (temperatures) as columns.总而言之,我有一个 pandas dataframe ,日期作为数据时间索引,浮动(温度)作为列。 I would like to sort rekords of this dataframe by monts of measurement, to achieve sth like this:我想通过测量来对这个 dataframe 的记录进行排序,以实现这样的目的:

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

How to do that?怎么做? I have tried:我努力了:

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

but it does not work like that I guess, so is there any way to do thay using build in sorting/groupby panadas methods (or similar).但它不像我猜的那样工作,所以有什么方法可以使用内置排序/groupby panadas 方法(或类似方法)来做到这一点。

Thanks in advance:).提前致谢:)。

You can create two additional columns (you can drop them later) and then you can sort according to those columns您可以创建两个额外的列(您可以稍后删除它们),然后您可以根据这些列进行排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM