Search code examples
pythonpandasdataframeplotly

How to change rows name to column name in dataframe using python?


i have two dataframe:

  df1:
     colname   value
     gender     M
     status     business
     age        60

  df2:
     colname   value
     name       Susan
     Place      Africa
     gender     F

Is there a way i can concatenate these two dataframe in a way as the expected output? I tried outer join but it doesnot work, Thank you in advance.

Note: No dataframes have always the same common attribute, and also I am trying to remove the colname and value column.

Expected output:

    gender status     age  name  Place 
0    M     business   60   0      0
1    F     0           0   Susan Africa

Solution

  • You can convert to Series with colname as index and concat:

    dfs = [df1, df2]
    
    out = pd.concat([d.set_index('colname')['value'] for d in dfs],
                    axis=1, ignore_index=True).T
    

    output:

    colname gender    status  age   name   Place
    0            M  business   60    NaN     NaN
    1            F       NaN  NaN  Susan  Africa