0

I have the following dataframe:

             ID      Date    Element  Data_Value Month_Day
143873  USW00014833 2005-01-02  TMIN    -0.6    01-02
74019   USW00094889 2005-01-02  TMIN    -0.6    01-02
112671  USC00200032 2005-01-02  TMAX    12.2    01-02

I want to group by the "Month_Day" column and sort by the values in "Data_Value", but still keep the dataframe format and the other columns.

I have tried the following code:

df = df.groupby('Month_Day')['Data_Value'].sort_values()

However, by this method I lose the other columns and the output is a series(I believe).

Any advice? Many thanks.

user2629628
  • 161
  • 1
  • 3
  • 11

2 Answers2

0

You can just sort on two columns:

df = df.sort_values(['Month_Day', 'Data_Value'])
halfer
  • 19,824
  • 17
  • 99
  • 186
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
0

If you want to use groupby. As in the link bellow, you need to groupby using list of columns that you want to keep and then call reset_index()

How to GroupBy a Dataframe in Pandas and keep Columns

Sebastian
  • 551
  • 2
  • 8