Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing 'upper level name' of pandas multi-index

I’m trying to learn how to use Pandas crosstab functionality but I can’t find way to access ‘upper level name’ of multi-index dataframe that crosstab produces. Simple example:

df_test = pd.DataFrame.from_dict({'A': [1, 2, 3], 'B': [4, 5, 6]}, orient='index')
df_test2 = pd.crosstab(df_test[0], df_test[1], margins=True)

print(df_test2.index.names)

Index.names gives me only ‘0’ but want to get list like [‘1′,’2′,’5’].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your dataframe produces the following result:

enter image description here

>>> df_test2.columns.name
1

>>> df_test2.columns
Index([2, 5, 'All'], dtype='object', name=1)  # <- Note the 1 as name
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading