Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multi column index in pandas

Tags:

I make dataframe like this.

df = pd.DataFrame({     'class' : ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],     'number' : [1,2,3,4,5,1,2,3,4,5],     'math' : [90, 20, 50, 30, 57, 67, 89, 79, 45, 23],     'english' : [40, 21, 68, 89, 90, 87, 89, 54, 21, 23] }) 

and i want to convert index to this by using some pandas methods.(ex. set_index, stack,,,)

df1 = pd.DataFrame(np.random.randint(1, 100, (5, 4)),              columns = [['A', 'A', 'B', 'B'],['english', 'math', 'english', 'math']],              index = [1, 2, 3, 4, 5]) 

how can i do this?

like image 778
alexmoon Avatar asked Dec 18 '16 13:12

alexmoon


People also ask

How do I create a multiple index column in pandas?

pandas MultiIndex to ColumnsUse pandas DataFrame. reset_index() function to convert/transfer MultiIndex (multi-level index) indexes to columns. The default setting for the parameter is drop=False which will keep the index values as columns and set the new index to DataFrame starting from zero.

How do I change multiple indexes to single index in pandas?

Output: Now, the dataframe has Hierarchical Indexing or multi-indexing. To revert the index of the dataframe from multi-index to a single index using the Pandas inbuilt function reset_index(). Returns: (Data Frame or None) DataFrame with the new index or None if inplace=True.


1 Answers

I think you need set_index with unstack for reshaping, then swap levels in MultiIndex in columns by swaplevel and last sort columns by sort_index:

df1 = df.set_index(['number','class']).unstack().swaplevel(0,1,1).sort_index(1)  print (df1) class        A            B             english math english math number                           1           40   90      87   67 2           21   20      89   89 3           68   50      54   79 4           89   30      21   45 5           90   57      23   23 

Another solution with stack and unstack:

print (df.set_index(['number','class']).stack().unstack([1,2])) class        A            B             english math english math number                           1           40   90      87   67 2           21   20      89   89 3           68   50      54   79 4           89   30      21   45 5           90   57      23   23 
like image 137
jezrael Avatar answered Oct 14 '22 00:10

jezrael