如何重新索引多索引pandas数据帧?

时间:2014-12-24 09:10:52

标签: python pandas multi-index reindex

给出以下pandas.core.frame.DataFrame,名为sorted_by_diff

In [10]:sorted_by_diff.head(4)

Out[10]:
           value
y          0         1          diff
variable            
george     1.265265  0.001550   1.263716
hp         0.895473  0.017479   0.877994
hpl        0.431994  0.009173   0.422822
re         0.415760  0.125091   0.290669

拥有以下列:

In [11]: sorted_by_diff.columns
Out[11]:
MultiIndex(levels=[[u'value'], [0, 1, u'diff']],
           labels=[[0, 0, 0], [0, 1, 2]],
           names=[None, u'y'])

以下索引:

In [12]: sorted_by_diff.index

Out[12]:
Index([u'george', u'hp', u'hpl', u're', u'edu', u'meeting', u'650', u'85', u'lab', u'labs', u'1999', u'data', u'project', u'technology', u'pm', u'telnet', u'address', u'857', u'415', u'cs', u'original', u'(', u'conference', u'direct', u';', u'[', u'parts', u'table', u'will', u'report', u'#', u'make', u'people', u'receive', u'addresses', u'over', u'order', u'$', u'3d', u'internet', u'mail', u'font', u'money', u'credit', u'all', u'email', u'business', u'000', u'remove', u'our', u'!', u'free', u'your', u'you', u'length_average', u'length_longest', u'length_total'], dtype='object')

如何rexindex sorted_by_diff是这样的?

           value
y          email     spam       diff
variable            
george     1.265265  0.001550   1.263716
hp         0.895473  0.017479   0.877994
hpl        0.431994  0.009173   0.422822
re         0.415760  0.125091   0.290669

也就是说,如何将索引级别0和1分别更改为“电子邮件”和“垃圾邮件”?

1 个答案:

答案 0 :(得分:1)

>>> sorted_by_diff.columns.set_levels([[u'value'], ['email', 'spam', 'diff']], inplace=True)
>>> sorted_by_diff
             value                    
y            email      spam      diff
variable                              
george    1.265265  0.001550  1.263716
hp        0.895473  0.017479  0.877994
hpl       0.431994  0.009173  0.422822
re        0.415760  0.125091  0.290669