I have forecast data that I grouped by month. The original dataframe something like this:
>>clean_table_grouped[0:5]
STYLE COLOR SIZE FOR
MONTH 01/17 10/16 11/16 12/16
0 ####### ###### #### 0.0 15.0 15.0 15.0
1 ####### ###### #### 0.0 15.0 15.0 15.0
2 ####### ###### #### 0.0 15.0 15.0 15.0
3 ####### ###### #### 0.0 15.0 15.0 15.0
4 ####### ###### #### 0.0 15.0 15.0 15.0
>>clean_table_grouped.ix[0:,"FOR"][0:5]
MONTH 01/17 10/16 11/16 12/16
0 0.0 15.0 15.0 15.0
1 0.0 15.0 15.0 15.0
2 0.0 15.0 15.0 15.0
3 0.0 15.0 15.0 15.0
4 0.0 15.0 15.0 15.0
I simply want reorder these 4 columns in the follow way:
(keeping the rest of the dataframe untouched)
MONTH 10/16 11/16 12/16 01/17
0 15.0 15.0 15.0 0.0
1 15.0 15.0 15.0 0.0
2 15.0 15.0 15.0 0.0
3 15.0 15.0 15.0 0.0
4 15.0 15.0 15.0 0.0
My attempted solution was to reorder the columns of the subset following the post below: How to change the order of DataFrame columns?
I went about it by grabbing the column list and sorting it first
>>for_cols = clean_table_grouped.ix[:,"FOR"].columns.tolist()
>>for_cols.sort(key = lambda x: x[0:2]) #sort by month ascending
>>for_cols.sort(key = lambda x: x[-2:]) #then sort by year ascending
Querying the dataframe works just fine
>>clean_table_grouped.ix[0:,"FOR"][for_cols]
MONTH 10/16 11/16 12/16 01/17
0 15.0 15.0 15.0 0.0
1 15.0 15.0 15.0 0.0
2 15.0 15.0 15.0 0.0
3 15.0 15.0 15.0 0.0
4 15.0 15.0 15.0 0.0
However, when I try to set values in the original table, I get a table of "NaN":
>>clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,"FOR"][for_cols]
>>clean_table_grouped.ix[0:,"FOR"]
MONTH 01/17 10/16 11/16 12/16
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
5 NaN NaN NaN NaN
I have also tried zipping to avoid chained syntax (.ix[][]). This avoids the NaN, however, it doesn't change the dataframe -__-
>>for_cols = zip(["FOR", "FOR", "FOR", "FOR"], for_cols)
>>clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,for_cols]
>>clean_table_grouped.ix[0:,"FOR"]
MONTH 01/17 10/16 11/16 12/16
0 0.0 15.0 15.0 15.0
1 0.0 15.0 15.0 15.0
2 0.0 15.0 15.0 15.0
3 0.0 15.0 15.0 15.0
4 0.0 15.0 15.0 15.0
I realize I'm using ix to reassign values. However, I've used this technique in the past on dataframes that are not grouped and it has worked just fine.
If this question as already been answered in another post (in a CLEAR way), please provide the link. I searched but could not find anything similar.
EDIT: I have found a solution. Manually reindex by creating a new multiindex dataframe in the order you want your columns sorted. I posted the solution below.