Pandas 为 MultiIndex 添加 Header 行

Pandas Add Header Row for MultiIndex

给定以下数据框:

d2=pd.DataFrame({'Item':['y','y','z','x'],
                'other':['aa','bb','cc','dd']})
d2

    Item    other
0   y       aa
1   y       bb
2   z       cc
3   x       dd

我想在顶部添加一行,然后将其用作 multiIndexed header 的级别 1。我不能总是预测数据框会有多少列,所以新行应该考虑到这一点(即随机字符或数字都可以)。 我正在寻找这样的东西:

    Item    other
    A       B
0   y       aa
1   y       bb
2   z       cc
3   x       dd

但同样,列数会有所不同且无法预测。

提前致谢!

我想你可以先通过 shape and then create list by range. Last create MultiIndex.from_tuples 找到列数。

print (d2.shape[1])
2

print (range(d2.shape[1]))
range(0, 2)

cols = list(zip(d2.columns, range(d2.shape[1])))
print (cols)
[('Item', 0), ('other', 1)]

d2.columns = pd.MultiIndex.from_tuples(cols)
print (d2)

  Item other
     0     1
0    y    aa
1    y    bb
2    z    cc
3    x    dd

如果您需要字母列并且列数少于 26,请使用:

import string
print (list(string.ascii_uppercase))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

print (d2.shape[1])
2

print (list(string.ascii_uppercase)[:d2.shape[1]])
['A', 'B']

cols = list(zip(d2.columns, list(string.ascii_uppercase)[:d2.shape[1]]))
print (cols)
[('Item', 'A'), ('other', 'B')]

d2.columns = pd.MultiIndex.from_tuples(cols)
print (d2)
  Item other
     A     B
0    y    aa
1    y    bb
2    z    cc
3    x    dd