Home > Software engineering >  How to change rows name to column name in dataframe using python?
How to change rows name to column name in dataframe using python?

Time:09-28

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related