BigDO
BigDO

Reputation: 13

Sorting Pandas dataframe hours by date

I made a dataframe by importing a CSV file. And I converted the date column to datetime and separated hours. And I replaced the hours 24 to 0 to be placed in the first row.

replace 24 to 0:

df['Hour'] = df['Hour'].replace([24], 0)
df

Here's the result:

           Hour  Value
Date        
2016-01-01  1   -1.09
2016-01-01  2   -2.41
2016-01-01  12  0.00
2016-01-01  13  0.00
2016-01-01  14  0.00
2016-01-01  0   0.00
... ... ...
2020-12-31  20  19.69
2020-12-31  21  20.78
2020-12-31  22  27.85
2020-12-31  23  19.68
2020-12-31  0   27.37

Also, I've been trying to sort the hour column by date. However, when sorting the hour it doesn't produce the result I wanted. What should I code to get the table below example:

For example (this is a desire table),

           Hour  Value
Date        
2016-01-01  0   0.00
2016-01-01  1   -1.09
2016-01-01  2   -2.41
2016-01-01  12  0.00
2016-01-01  13  0.00
2016-01-01  14  0.00
2017-01-01  0   0.00
2017-01-01  1   -5.03
2017-01-01  2   -2.75
2017-01-01  3  4.32
2017-01-01  4  0.00
2017-01-01  5  1.45
... ... ...
2020-12-31  0   27.37
2020-12-31  20  19.69
2020-12-31  21  20.78
2020-12-31  22  27.85
2020-12-31  23  19.68

I know this could be annoying you guys but, I would really appreciate your help...

Upvotes: 1

Views: 153

Answers (1)

Youssef_boughanmi
Youssef_boughanmi

Reputation: 379

you can use df.sort_values()

df.sort_values(['Date', 'Hour'], ascending=[True, True])

Upvotes: 2

Related Questions