python - 来自不规则元组的 MultiIndex

标签 python pandas multi-index

我有以下元组

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

enter image description here

关于python - 来自不规则元组的 MultiIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38671810/

相关文章:

python - 当没有文本但也没有图像时,如何按像素调整 Tkinter Checkbutton 的大小?

python - 将 PIL 图像转换为字节数组

python - 使用 groupby 将分组数据转换为数据帧

python - 如何根据多索引 Pandas 数据框中的索引级别获取小计

python - 如何连接多索引列数据框

python - opencv haar文件返回太多面部特征

python - GroupBy 操作使用整个数据框对值进行分组

python - Pandas,有没有更快的更新值的方法?

c++ - 如何迭代 multi_index

python - 从给定范围内选择整数