Search code examples
pythonpandaspivot-tablemulti-index

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'].


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