You can create MultiIndex
:
df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
Specified new name of level with start and end column name:
L = [('OBS','A','C'), ('FIN', 'D','F')]
And then in list comprehension create tuples
for MultiIndex.from_tuples
:
cols = [(new, c) for new, start, end in L for c in df.loc[:, start:end].columns]
print (cols)
[('OBS', 'A'), ('OBS', 'B'), ('OBS', 'C'), ('FIN', 'D'), ('FIN', 'E'), ('FIN', 'F')]
df.columns = pd.MultiIndex.from_tuples(cols)
print (df)
OBS FIN
A B C D E F
0 a 4 7 1 5 a
1 b 5 8 3 3 a
2 c 4 9 5 6 a
3 d 5 4 7 9 b
4 e 5 2 1 2 b
5 f 4 3 0 4 b