17
votes

I am building a new method to parse a DataFrame into a Vincent-compatible format. This requires a standard Index (Vincent can't parse a MultiIndex).

Is there a way to detect whether a Pandas DataFrame has a 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.)

4
name 'pandas' is not defined you should import pandas first! - Winand

4 Answers

31
votes

You can use isinstance to check whether an object is a class (or its subclasses):

if isinstance(result.index, pandas.MultiIndex):
8
votes

You can use nlevels to check how many levels there are:

df.index.nlevels 
df.columns.nlevels 

If nlevels > 1, your dataframe certainly has multiple indices.

7
votes

There's also

len(result.index.names) > 1

but it is considerably slower than either isinstance or 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
0
votes

Maybe the shortest way is if type(result.index)==pd.MultiIndex: