How do you update the levels of a pandas MultiIndex after slicing its DataFrame?

后端 未结 3 699
借酒劲吻你
借酒劲吻你 2020-11-27 05:55

I have a Dataframe with a pandas MultiIndex:

In [1]: import pandas as pd
In [2]: multi_index = pd.MultiIndex.from_product([[\'CAN\',\'USA\'],[\'total\']],nam         


        
3条回答
  •  一向
    一向 (楼主)
    2020-11-27 06:45

    This is something that has bitten me before. Dropping columns or rows does NOT change the underlying MultiIndex, for performance and philosophical reasons, and this is officially not considered a bug (read more here). The short answer is that the developers say "that's not what the MultiIndex is for". If you need a list of the contents of a MultiIndex level after modification, for example for iteration or to check to see if something is included, you can use:

    df.index.get_level_values()
    

    This returns the current active values within that index level.

    So I guess the "trick" here is that the API native way to do it is to use get_level_values instead of just .index or .columns

提交回复
热议问题