来自不规则元组的 MultiIndex

MultiIndex from irregular tuple of 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'))]

我想从中创建一个 pandas MultiIndex

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

但是我在第二层得到了元组。我如何获得所有三个级别?

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

您必须展平您的元组。我是这样做的

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