pandas 为MultiIndex添加标题行 [英] Pandas Add Header Row for MultiIndex

查看:42
本文介绍了 pandas 为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标头的1级.我不能总是预测数据帧将有多少列,因此新行应允许这样做(即,可以使用随机字符或数字). 我正在寻找这样的东西:

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.

提前谢谢!

推荐答案

我认为您可以先通过 MultiIndex.from_tuples .

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

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

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

这篇关于 pandas 为MultiIndex添加标题行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆