I'm trying to loop over a set of tables in a particular way but I'm stuck.
My tables are multiindex and look like this:
#read excel
df = pd.read_excel(data_file,
header=[0,1],
index_col=[0,1])
T Gender Age
Total Male Female 16-24 25-34 35-44 45-54 55-75
Q1. Are you? Yes 17.5 26.8 23.4 13.7 20.7 100 - 17.6
No 17.5 26.8 23.4 13.7 20.7 100 11.5 22.6
Don’t know 17.5 26.8 23.4 13.7 20.7 100 - -
Q2. Are you? Yes 18.5 26.8 23.4 13.7 20.7 100 - 17.6
No 17.5 22.8 23.4 13.7 20.7 100 11.5 22.6
Don’t know 17.5 26.8 23.4 13.7 20.7 100 - -
I would like to loop over these indexes and columns and print this:
T
Total
Q1. Are you? Yes 17.5
No 17.5
Don’t know 17.5
Gender
Male Female
Q1. Are you? Yes 26.8 23.4
No 26.8 23.4
Don’t know 26.8 23.4
and so forth....
My code so far groups the outter indexs together which allows me to loop downwards but I dont know how to work my way across horizontally..?
for outerside_grp, innerside_grp in df.groupby(level=0):
print innerside_grp
UPDATE
Code below kinda of does what I want (thanks to Joshua Baboo) but now I'm wondering if it's the most effient method?
for key in df.index.levels[0]:
for col in df.columns.levels[0]:
print df.loc[row:row, col]