Phil Sheard
Phil Sheard

Reputation: 2162

Detect whether a dataframe has a MultiIndex

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.)

Upvotes: 31

Views: 29673

Answers (4)

jonrsharpe
jonrsharpe

Reputation: 122103

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

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

Upvotes: 49

k0rnik
k0rnik

Reputation: 502

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.

Upvotes: 19

danio
danio

Reputation: 8653

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

Upvotes: 7

avs
avs

Reputation: 65

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

Upvotes: 0

Related Questions