Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Pandas : How many levels in a dataframe index?

Tags:

python

pandas

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_levels to hold the result, i can do the following if the dataframe has a multi-index :

>>> nb_levels = len(df.index[0])    
nb_levels = 2

assuming a 2-levels multi-index

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 ?

like image 690
knightofni Avatar asked Feb 19 '14 09:02

knightofni


People also ask

How many indices does a DataFrame have?

But for now here's my answer: DataFrame is 2 dimensional, and its index are rows and columns (2 indexes) .

What are index levels in pandas?

Visualisations also need good control over pandas index. Index is like an address, that's how any data point across the dataframe or series can be accessed. Rows and columns both have indexes, rows indices are called as index and for columns its general column names.

How do you count indexes in pandas?

You can use len(df. index) to find the number of rows in pandas DataFrame, df. index returns RangeIndex(start=0, stop=8, step=1) and use it on len() to get the count.

Does pandas DataFrame have index?

The index property returns the index information of the DataFrame. The index information contains the labels of the rows. If the rows has NOT named indexes, the index property returns a RangeIndex object with the start, stop, and step values.


1 Answers

Each Dataframe has an attribute holding the amount of levels:

nblevels = df.index.nlevels 
like image 177
Rutger Kassies Avatar answered Oct 08 '22 19:10

Rutger Kassies