Brian Brian - 4 months ago 17
Python Question

MultiIndex from irregular tuple of tuples

I have the following tuples

tups = zip(list('AAAABBBB'), zip(list('aabbaabb'), list('cdcdcdcd')))

tups

[('A', ('a', 'c')),
('A', ('a', 'd')),
('A', ('b', 'c')),
('A', ('b', 'd')),
('B', ('a', 'c')),
('B', ('a', 'd')),
('B', ('b', 'c')),
('B', ('b', 'd'))]


I'd like to create a pandas MultiIndex from them

df = pd.DataFrame(np.arange(32).reshape(4, 8),
columns=pd.MultiIndex.from_tuples(tups))


But I get tuples in a second level. How do I get all three levels?

print df

A B
(a, c) (a, d) (b, c) (b, d) (a, c) (a, d) (b, c) (b, d)
0 0 1 2 3 4 5 6 7
1 8 9 10 11 12 13 14 15
2 16 17 18 19 20 21 22 23
3 24 25 26 27 28 29 30 31

Answer

You'll have to flatten your tuples. I did it as follows

new_tups = [(a, b, c) for a, (b, c) in tups]

df = pd.DataFrame(np.arange(32).reshape(4, 8),
                  columns=pd.MultiIndex.from_tuples(new_tups))

enter image description here