Dataframe
TYPE WEEK VALUE1 VALUE2
0 Type1 1 1 1
1 Type2 2 2 2
2 Type3 3 3 3
3 Type4 4 4 4
import pandas as pd
import numpy as np
df = {'TYPE' : pd.Series(['Type1','Type2','Type3','Type4']),
'WEEK' : pd.Series([1, 2, 3, 4]),
'VALUE1' : pd.Series([1, 2, 3, 4]),
'VALUE2' : pd.Series([1, 2, 3, 4])
}
df = pd.DataFrame(df)
df = pd.pivot_table(df,index="TYPE",columns="WEEK", values=['VALUE1','VALUE2']).reset_index()
df2 = df.swaplevel(0,1,axis=1).reset_index()
Output
WEEK index 1 2 3 4 1 2 3 4
TYPE VALUE1 VALUE1 VALUE1 VALUE1 VALUE2 VALUE2 VALUE2 VALUE2
0 0 Type1 1.0 NaN NaN NaN 1.0 NaN NaN NaN
1 1 Type2 NaN 2.0 NaN NaN NaN 2.0 NaN NaN
2 2 Type3 NaN NaN 3.0 NaN NaN NaN 3.0 NaN
3 3 Type4 NaN NaN NaN 4.0 NaN NaN NaN 4.0
Expected structure output
WEEK TYPE | VALUE11 VALUE21 | VALUE12 VALUE22 | VALUE13 VALUE23 | VALUE14 VALUE24
0 Type1 | | | |
1 Type2 | | | |
2 Type3 | | | |
3 Type4 | | | |
Approaches in thought:
- Reorder the structure. (I have tried
swaplevel()
as above but cannot attain the expected output) - Join the columns name eg. "Value11" by "Value1" + "1" I have looked through several examples from the internet but cannot come up with anything.