I have this pandas df which i imported from a csv:
df 0 0 apple banana orange dates apple banana orange 1 1 1 1 1 Friday, January 01, 2021 1 1 1 2 2 1 1 1 Saturday, January 02, 2021 2 2 2 3 3 1 1 1 Sunday, January 03, 2021 3 3 3 4 4 1 1 1 Monday, January 04, 2021 4 4 4 5 5 1 1 1 Tuesday, January 05, 2021 5 5 5 6 6 1 1 1 Wednesday, January 06, 2021 6 6 6 7 7 1 1 1 Thursday, January 07, 2021 7 7 7 8 8 1 4 1 Friday, January 08, 2021 8 8 8 9 9 1 1 1 Saturday, January 09, 2021 9 9 9
Is it possible for everything on the left to be grouped under fresh
and everything on the right of the dates to be under column spoil
in multiindex format. Such as, there is one column which contains [apple, banana, orange]. I want to do this because later when i set the date as index there would be no confusion as both sides of the column have the same names.
Advertisement
Answer
df.columns = pd.MultiIndex.from_arrays([['', '', 'fresh', 'fresh', 'fresh', '', 'spoil', 'spoil', 'spoil'], df.columns])
output:
fresh spoil 0 0 apple banana orange dates apple banana orange 0 1 1 1 1 1 Friday, January 01, 2021 1 1 1 1 2 2 1 1 1 Saturday, January 02, 2021 2 2 2 2 3 3 1 1 1 Sunday, January 03, 2021 3 3 3 3 4 4 1 1 1 Monday, January 04, 2021 4 4 4 4 5 5 1 1 1 Tuesday, January 05, 2021 5 5 5 5 6 6 1 1 1 Wednesday, January 06, 2021 6 6 6 6 7 7 1 1 1 Thursday, January 07, 2021 7 7 7 7 8 8 1 4 1 Friday, January 08, 2021 8 8 8 8 9 9 1 1 1 Saturday, January 09, 2021 9 9 9
NB. if you want to set_index('dates')
do it before this operation, this will be easier