close

[Solved] ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe Error Occurs?

Today I get the following error ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe in python.

How To Solve ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe Error ?

  1. How To Solve ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe Error ?

    To Solve ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe Error The problem is that you have an empty data frame which has zero columns, and you are trying to assign a four columns multi-index to it;

  2. ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe

    To Solve ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe Error The problem is that you have an empty data frame which has zero columns, and you are trying to assign a four columns multi-index to it;

Solution 1

The problem is that you have an empty data frame which has zero columns, and you are trying to assign a four columns multi-index to it; If you create an empty data frame of four columns initially, the error will be gone:

df = pd.DataFrame(pd.np.empty((0, 4)))    
df.columns = pd.MultiIndex(levels = [['first', 'second'], ['a', 'b']], labels = [[0, 0, 1, 1], [0, 1, 0, 1]])

Or you can create empty data frame with the multi-index as follows:

multi_index = pd.MultiIndex(levels = [['first', 'second'], ['a', 'b']], labels = [[0, 0, 1, 1], [0, 1, 0, 1]])    
df = pd.DataFrame(columns=multi_index)

df
#   first    second
#  a    b   a     b

Solution 2

This solution does not require numpy:

# create empty DataFrame with 4 columns
df = pd.DataFrame(columns = range(4))

df.columns = pd.MultiIndex(
    levels = [['first', 'second'], ['a', 'b']], 
    codes = [[0, 0, 1, 1], [0, 1, 0, 1]]
)

(Note: I changed labels to codes because that was changed in Pandas v1.0.0)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read