Pandas Add Header Row for MultiIndex

丶灬走出姿态 提交于 2019-12-23 01:18:49

问题


Given the following data frame:

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

I'd like to add a row to the top and then use that as level 1 of a multiIndexed header. I can't always predict how many columns the data frame will have, so the new row should allow for that (i.e. random characters or numbers are okay). I'm looking for something like this:

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

But again, the number of columns will vary and cannot be predicted.

Thanks in advance!


回答1:


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


来源:https://stackoverflow.com/questions/37364859/pandas-add-header-row-for-multiindex

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