0

I have the code below that creates new columns in my dataframe for median sold and std sold. The problem I have is that I don't want the multi-index output. How can I flatten the output like the desired output example below? Or is there a way to just create the new columns as aggregations of sold without creating the multi index in the first place.

Maybe something like in sql: 

select Month, M_day, median(sold) as median, std(sold) as std from month_df group by Month, M_day


Code:
month_df=month_df[['Month','M_day','sold']].groupby(['Month','M_day']).agg(['median','std'])
print(month_df.head())


Output:

              sold           
            median        std
Month M_day                  
1     2       12.0  13.719555
      3        5.0  11.508762
      4       12.0  12.907761
      5        6.0  14.371283
      6       12.0   7.859340

desired output:



Month M_day  median        std              
1     2       12.0  13.719555
      3        5.0  11.508762
      4       12.0  12.907761
      5        6.0  14.371283
      6       12.0   7.859340
user3476463
  • 3,967
  • 22
  • 57
  • 117
  • @jpp Thank you for getting back to me so quickly. The two answers that you sent me seem a little different. Since I'm creating two aggregations from one field instead of one aggregation. The solution I've come up with is to create one dataframe with std, and reset_index. Then create another dataframe with median and reset_index. Then join them on Month and M_day. Is that really the best way to achieve this? – user3476463 May 28 '18 at 20:05
  • The solutions across the 2 duplicates should deal with *any* scenario where indices or columns are MultiIndex. What I suggest you do is if you are having trouble applying a solution is to show your attempt (via the solutions provided) and what you get instead of your desired result. Feel free to [edit](https://stackoverflow.com/posts/50545729/edit) your question with this improvement. Good luck! – jpp May 28 '18 at 20:07

0 Answers0