Search code examples
pandasmulti-index

How to retain multiindex in pandas dataframe while concatenate two separate dataframe


enter image description here

dfs_subs dataframe contain multiindex one level is Question-0 and next level is (Score,..) and i have other dataframe which is having only one level.When i am doing table_1 = pd.concat([df_metadata, dfs_subs], axis=1, levels=0)

table_1 output is showing like below

enter image description here

but i want Question-0 should be one separate level instead of combined as one single column.

For example:

enter image description here


Solution

  • If need MultiIndex in both is possible add empty values for second level for MultiIndex in both DataFrames:

    df1.columns = pd.MultiIndex.from_product([df1.columns, ['']])
    print (df1)
      Name Age
              
    0  Sam  43
    
    #check how looks MultiIndex converted to list
    print (df1.columns.tolist())
    [('Name', ''), ('Age', '')]
    

    df = pd.concat([df1, df2], axis=1)
    print (df)
      Name Age Address  Fav
                 score Time
    0  Sam  43       7   10
    
    #check how looks MultiIndex converted to list
    print (df.columns.tolist())
    [('Name', ''), ('Age', ''), ('Address', 'score'), ('Fav', 'Time')]