Renaming index values in multiindex dataframe

前端 未结 2 1640
时光取名叫无心
时光取名叫无心 2021-02-02 18:21

Creating my dataframe:

from pandas import *
arrays = [[\'bar\', \'bar\', \'baz\', \'baz\', \'foo\', \'foo\', \'qux\', \'qux\'],
          [\'one\', \'two\', \'o         


        
2条回答
  •  灰色年华
    2021-02-02 18:49

    The set_levels method was causing my new column names to be out of order. So I found a different solution that isn't very clean, but works well. The method is to print df.index (or equivalently df.columns) and then copy and paste the output with the desired values changed. For example:

    print data.index
    

    MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']], labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]], names=['first', 'second'])

    data.index = MultiIndex(levels=[['new_bar', 'new_baz', 'new_foo', 'new_qux'],
                                    ['new_one', 'new_two']],
                            labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
                            names=['first', 'second'])
    

    We can have full control over names by editing the labels as well. For example:

    data.index = MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'],
                                    ['one', 'twooo', 'three', 'four',
                                     'five', 'siz', 'seven', 'eit']],
                            labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 2, 3, 4, 5, 6, 7]],
                            names=['first', 'second'])
    

    Note that in this example we have already done something like from pandas import MultiIndex or from pandas import *.

提交回复
热议问题