Pandas Add Header Row for MultiIndex

陌路散爱 提交于 2019-12-06 16:31:19

I think you can first find number of columns by 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

If you need alphabet columns and number of columns is less as 26, use:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!