2016-07-30 9 views
1

Ich habe die folgende TupelMultiindex aus unregelmäßigen Tupel von Tupeln

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'))] 

Ich mag würde eine Pandas Multiindex von ihnen

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

Aber ich bekomme Tupel in einer zweiten Ebene zu erstellen. Wie bekomme ich alle drei Ebenen?

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 

Antwort

1

Sie müssen Ihre Tupel reduzieren. Ich habe es wie folgt

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

Verwandte Themen