i have a df and i have some questions.
i need to change one column from the df to the superior level of the header: column ->level 0 axis 1.
and the other way from multilevel df, take the level 0 and put it in the df. level0 axis 1 -> columns
but i searched on the web if there are other methods more straightforward
because it seemed a bit complicated some times .
i ask here because it took me some longs hours to understand the documentation and i m not sure if there is a better method
first case. from:
df name0| a , b , ,
index name1| aa ee cc dd bb
-------------|--------------------------
0 | 1 5 8 8 7
1 | 4 7 8 9 5
to:
df
index name1| name0 aa ee cc dd bb
-------------|-------------------------------
0 | a 1 5 8 8 7
1 | a 4 7 8 9 5
i found
df.stack()reset_index(level='name0')
or second case. from:
df
index name1| name0 aa ee cc dd bb
-------------|-------------------------------
0 | a 1 5 8 8 7
1 | a 4 7 8 9 5
to:
df name0| a , b , ,
index name1| aa ee cc dd bb
-------------|--------------------------
0 | 1 5 8 8 7
1 | 4 7 8 9 5
i found
df.set_index('column,append=true).unstack(level='name0').swaplevel(axis=1).sort_index(axis=1,level=0)
or
df..set_index('column,append=true).stack().unstack( level=['name0', 'name1'] )
a las question is: how to reorder a multi level heade dataframe column in a specific order because those transformations sometimes mess the order and i need in in specific order
(actually it is not so important but i wanna know)
user3479215 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.