Python / Pandas:数据帧索引中有多少层?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21876200/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python / Pandas : How many levels in a dataframe index?
提问by knightofni
I need to know how many levels there are in a dataframe, without knowing if that dataframe has a Multi-index or a 'Normal' index.
我需要知道数据帧中有多少个级别,而不知道该数据帧是否具有多索引或“正常”索引。
Assuming a dataframe df, and a variable nb_levelsto hold the result, i can do the following if the dataframe has a multi-index :
假设有一个 dataframedf和一个nb_levels保存结果的变量,如果 dataframe 有一个 multi-index ,我可以执行以下操作:
>>> nb_levels = len(df.index[0])    
nb_levels = 2
assuming a 2-levels multi-index
假设一个 2 级多索引
So i could get my desired result like this :
所以我可以像这样得到我想要的结果:
try:
    df.index.get_level_values(1)
    nb_levels = 1
except:
    nb_levels = len(df.index[0])
But it feels like a horrible hack, and surely there must be simple way to get this result. Problem is that i can't seem to find it. Help ?
但这感觉就像一个可怕的黑客,当然必须有简单的方法来获得这个结果。问题是我似乎找不到它。帮助 ?
回答by Rutger Kassies
Each Dataframe has an attribute holding the amount of levels:
每个 Dataframe 都有一个包含级别数量的属性:
nblevels = df.index.nlevels 

