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 ?
But for now here's my answer: DataFrame is 2 dimensional, and its index are rows and columns (2 indexes) .
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.
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.
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.
Each Dataframe has an attribute holding the amount of levels:
nblevels = df.index.nlevels
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With