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

Question:

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
Asked By: Coder

||

Answers:

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
Answered By: mozway

Try this:

pd.concat([df1, df2], axis=0).fillna(0).reset_index(drop=True)

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

The fillna will replace the NaN values with 0.

Answered By: elementalchoas

Below line will resolves your issue , you can use the pandas transpose function to solve this problem.

df_new = pd.concat([df1,df2])
df_new.set_index("colname").T
Answered By: sujith kumar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.