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
Run Code Online (Sandbox Code Playgroud)
此功能非常有用,因为它允许同一数据帧的多个版本"水平"附加,第一级列名称(在我的示例中instance)区分实例.
想象一下,我已经拥有了这样的数据帧:
a b c
bar 0.102885 0.937838 0.907467
Run Code Online (Sandbox Code Playgroud)
有没有一种很好的方法可以为列名添加另一个级别,类似于行索引:
x['instance'] = 'first'
x.set_level('instance',append=True)
Run Code Online (Sandbox Code Playgroud) 我有两个数据帧,如下所示:
>>> df1
A B
2000-01-01 1.4 1.4
2000-01-02 1.7 -1.9
2000-01-03 -0.2 -0.8
>>> df2
A B
2000-01-01 0.6 -0.3
2000-01-02 -0.4 0.6
2000-01-03 1.1 -1.0
Run Code Online (Sandbox Code Playgroud)
如何使用下面的分层列索引从这两个中创建一个数据帧?
df1 df2
A B A B
2000-01-01 1.4 1.4 0.6 -0.3
2000-01-02 1.7 -1.9 -0.4 0.6
2000-01-03 -0.2 -0.8 1.1 -1.0
Run Code Online (Sandbox Code Playgroud)