pandas 检测数据帧是否具有 MultiIndex
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21081042/
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
Detect whether a dataframe has a MultiIndex
提问by Phil Sheard
I am building a new method to parse a DataFrameinto a Vincent-compatible format. This requires a standard Index(Vincent can't parse a MultiIndex).
我正在构建一种将 a 解析DataFrame为 Vincent 兼容格式的新方法。这需要一个标准Index(文森特无法解析 a MultiIndex)。
Is there a way to detect whether a Pandas DataFramehas a MultiIndex?
有没有办法检测PandasDataFrame是否有MultiIndex?
In: type(frame)
Out: pandas.core.index.MultiIndex
I've tried:
我试过了:
In: if type(result.index) is 'pandas.core.index.MultiIndex':
print True
else:
print False
Out: False
If I try without quotations I get:
如果我尝试不使用引号,我会得到:
NameError: name 'pandas' is not defined
Any help appreciated.
任何帮助表示赞赏。
(Once I have the MultiIndex, I'm then resetting the index and merging the two columns into a single string value for the presentation stage.)
(一旦我有了MultiIndex,我就会重置索引并将两列合并为一个字符串值以供演示阶段使用。)
回答by jonrsharpe
You can use isinstanceto check whether an object is a class (or its subclasses):
您可以使用isinstance来检查一个对象是否是一个类(或其子类):
if isinstance(result.index, pandas.MultiIndex):
回答by danio
There's also
还有
len(result.index.names) > 1
but it is considerably slower than either isinstance or type:
但它比 isinstance 或 type 慢得多:
timeit(len(result.index.names) > 1)
The slowest run took 10.95 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.12 μs per loop
In [254]:
timeit(isinstance(result.index, pd.MultiIndex))
The slowest run took 30.53 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 177 ns per loop
In [252]:
)
timeit(type(result.index) == pd.MultiIndex)
The slowest run took 22.86 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 200 ns per loop
回答by k0rnik
You can use nlevelsto check how many levels there are:
您可以使用nlevels来检查有多少个级别:
df.index.nlevels
df.columns.nlevels
If nlevels > 1, your dataframe certainly has multiple indices.
如果nlevels > 1,您的数据框肯定有多个索引。
回答by avs
Maybe the shortest way is if type(result.index)==pd.MultiIndex:
也许最短的路是if type(result.index)==pd.MultiIndex:

