Giving a column multiple indexes/headers
You can use multiIndex to give multiple columns with names for each level. Use MultiIndex.from_product()
to make multiIndex from cartesian products of multiple iterables.
header = pd.MultiIndex.from_product([['location1','location2'],
['S1','S2','S3']],
names=['loc','S'])
df = pd.DataFrame(np.random.randn(5, 6),
index=['a','b','c','d','e'],
columns=header)
Two levels will be loc and S.
df
loc location1 location2
S S1 S2 S3 S1 S2 S3
a -1.245988 0.858071 -1.433669 0.105300 -0.630531 -0.148113
b 1.132016 0.318813 0.949564 -0.349722 -0.904325 0.443206
c -0.017991 0.032925 0.274248 0.326454 -0.108982 0.567472
d 2.363533 -1.676141 0.562893 0.967338 -1.071719 -0.321113
e 1.921324 0.110705 0.023244 -0.432196 0.172972 -0.50368
Now you can use xs to slice the dateframe based on levels.
df.xs('location1',level='loc',axis=1)
S S1 S2 S3
a -1.245988 0.858071 -1.433669
b 1.132016 0.318813 0.949564
c -0.017991 0.032925 0.274248
d 2.363533 -1.676141 0.562893
e 1.921324 0.110705 0.02324
df.xs('S1',level='S',axis=1)
loc location1 location2
a -1.245988 0.105300
b 1.132016 -0.349722
c -0.017991 0.326454
d 2.363533 0.967338
e 1.921324 -0.43219