It should be simple:
wide_df = pandas.read_excel(xlfile, sheetname, header=[0, 1, 2], index_col=[0, 1, 2, 3])
long_df = wide_df.stack().stack().stack()
CSV ( , ):
from io import StringIO
from textwrap import dedent
import pandas
mockcsv = StringIO(dedent("""\
num,,,this1,this1,this1,this1,that1,that1,that1,that1
let,,,thisA,thisA,thatA,thatA,thisB,thisB,thatB,thatB
animal,,,cat,dog,bird,lizard,cat,dog,bird,lizard
a,b,c,,,,,,,,
a1,b1,c1,x1,x2,x3,x4,x5,x6,x7,x8
a1,b1,c2,y1,y2,y3,y4,y5,y6,y7,y8
a1,b2,c1,z1,z2,z3,z4,z5,6z,zy,z8
"""))
wide_df = pandas.read_csv(mockcsv, index_col=[0, 1, 2], header=[0, 1, 2])
long_df = wide_df.stack().stack().stack()
wide_df :
num this1 that1
let thisA thatA thisB thatB
animal cat dog bird lizard cat dog bird lizard
a b c
a1 b1 c1 x1 x2 x3 x4 x5 x6 x7 x8
c2 y1 y2 y3 y4 y5 y6 y7 y8
b2 c1 z1 z2 z3 z4 z5 6z zy z8
long_df
a b c animal let num
a1 b1 c1 bird thatA this1 x3
thatB that1 x7
cat thisA this1 x1
thisB that1 x5
dog thisA this1 x2
thisB that1 x6
lizard thatA this1 x4
thatB that1 x8
c2 bird thatA this1 y3
thatB that1 y7
cat thisA this1 y1
thisB that1 y5
dog thisA this1 y2
thisB that1 y6
lizard thatA this1 y4
thatB that1 y8
b2 c1 bird thatA this1 z3
thatB that1 zy
cat thisA this1 z1
thisB that1 z5
dog thisA this1 z2
thisB that1 6z
lizard thatA this1 z4
thatB that1 z8
, OP, , , :
index_names = ['a', 'b', 'c']
col_names = ['Level1', 'Level2', 'Level3']
df = (
pandas.read_excel('Book1.xlsx', header=[0, 1, 2], index_col=[0, 1, 2, 3])
.reset_index(level=0, drop=True)
.rename_axis(index_names, axis='index')
.rename_axis(col_names, axis='columns')
.stack()
.stack()
.stack()
.to_frame()
)
, , , index_names .