Pandas: Modify a particular level of Multiindex

后端 未结 3 1582
旧巷少年郎
旧巷少年郎 2020-12-02 14:40

I have a dataframe with Multiindex and would like to modify one particular level of the Multiindex. For instance, the first level might be strings and I may want to remove t

3条回答
  •  被撕碎了的回忆
    2020-12-02 14:47

    As mentioned in the comments, indexes are immutable and must be remade when modifying, but you do not have to use reset_index for that, you can create a new multi-index directly:

    df.index = pd.MultiIndex.from_tuples([(x[0], x[1].replace(' ', ''), x[2]) for x in df.index])
    

    This example is for a 3-level index, where you want to modify the middle level. You need to change the size of the tuple for different level sizes.

    Update

    John's improvement is great performance-wise, but as mentioned in the comments it causes an error. So here's the corrected implementation with small improvements:

    df.index.set_levels(
        df.index.levels[0].str.replace(' ',''), 
        level=0,
        inplace=True,  # If False, you will need to use `df.index = ...`
    )
    

    If you'd like to use level names instead of numbers, you'll need another small variation:

    df.index.set_levels(
        df.index.levels[df.index.names.index('level_name')].str.replace(' ',''), 
        level='level_name',
        inplace=True,
    )
    

提交回复
热议问题