Reputation: 43
I have a problem with pandas dataframe indexed with datetime values, my dataframe temps
looks like this:
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. I would like to sort rekords of this dataframe by monts of measurement, to achieve sth like this :
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).
Thanks in advance :).
Upvotes: 1
Views: 295
Reputation: 9267
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'])
Upvotes: 2