Dance Party
Dance Party

Reputation: 3723

Pandas Add Header Row for MultiIndex

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!

Upvotes: 2

Views: 3541

Answers (1)

jezrael
jezrael

Reputation: 863531

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

Upvotes: 2

Related Questions