pandas: convert index type in multiindex dataframe

后端 未结 3 2043
别跟我提以往
别跟我提以往 2020-12-30 00:40

Hi have a multiindex dataframe:

tuples = [(\'YTA_Q3\', 1), (\'YTA_Q3\', 2), (\'YTA_Q3\', 3), (\'YTA_Q3\', 4), (\'YTA_Q3\', 99), (\'YTA_Q3\', 96)]
# Index
ind         


        
相关标签:
3条回答
  • 2020-12-30 01:19

    I find the current pandas implementation a bit cumbersome, so I use this:

    df1.index = pd.MultiIndex.from_tuples([(ix[0], str(ix[1])) for ix in df1.index.tolist()])

    0 讨论(0)
  • 2020-12-30 01:31

    There was change in pandas and old way doesn't work properly.

    For me this worked.

    level_to_change = 1
    df.index = df.index.set_levels(df.index.levels[level_to_change].astype(int), level=level_to_change)
    
    0 讨论(0)
  • 2020-12-30 01:42

    IIUC you need the last level of Multiindex. You could access it with levels:

    df1.index.levels[-1].astype(str)
    
    In [584]: df1.index.levels[-1].astype(str)
    Out[584]: Index(['1', '2', '3', '4', '96', '99'], dtype='object', name='Values')
    

    EDIT

    You could set your inner level with set_levels method of multiIndex:

    idx = df1.index
    df1.index = df1.index.set_levels([idx.levels[:-1], idx.levels[-1].astype(str)])
    
    0 讨论(0)
提交回复
热议问题