且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 pandas MultiIndex切片后,如何更新其水平?

更新时间:2023-02-02 17:24:02

这是我以前咬过的东西.出于性能和哲学上的考虑,删除列或行不会更改基础MultiIndex,并且正式不将其视为错误(

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(<levelname>)

这将返回该索引级别内的当前活动值.

This returns the current active values within that index level.

所以我想这里的窍门"是API的本机方法是使用get_level_values而不是.index或.columns

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