pandas :多级列名 [英] Pandas: Multilevel column names

查看:208
本文介绍了 pandas :多级列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pandas支持多级列名:

>>>  x = pd.DataFrame({'instance':['first','first','first'],'foo':['a','b','c'],'bar':rand(3)})
>>> x = x.set_index(['instance','foo']).transpose()
>>> x.columns
MultiIndex
[(u'first', u'a'), (u'first', u'b'), (u'first', u'c')]
>>> x
instance     first                    
foo              a         b         c
bar       0.102885  0.937838  0.907467

此功能非常有用,因为它允许水平"地将同一数据框的多个版本附加到区分实例的列名称的第一级(在我的示例中为instance).

This feature is very useful since it allows multiple versions of the same dataframe to be appended 'horizontally' with the 1st level of the column names (in my example instance) distinguishing the instances.

想象一下我已经有一个这样的数据框:

Imagine I already have a dataframe like this:

                 a         b         c
bar       0.102885  0.937838  0.907467

是否有一种向列名添加另一个级别的好方法,类似于行索引:

Is there a nice way to add another level to the column names, similar to this for row index:

x['instance'] = 'first'
x.set_level('instance',append=True)

推荐答案

无需创建元组列表

使用: pd.MultiIndex.from_product(iterables)

import pandas as pd
import numpy as np

df = pd.Series(np.random.rand(3), index=["a","b","c"]).to_frame().T
df.columns = pd.Multiindex.from_product([["new_label"], df.columns])

结果数据框:

  new_label                    
          a         b         c
0   0.25999  0.337535  0.333568

从2014年1月25日起请求拉

这篇关于 pandas :多级列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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