add dataframes columns names to rows after join procedure

Viewed 29

I have the following dataframe:

df1 = pd.DataFrame({'ID'    : ['T1002.', 'T5006.', 'T5007.'],
                    'Parent': ['Stay home.', "Stay home.","Stay home."],
                    'Child' : ['2Severe weather.', "5847..", "Severe weather."]})



      ID    Parent       Child
0   T1002.  Stay home.  2Severe weather.
1   T5006.  Stay home.  5847.
2   T5007.  Stay home.  Severe weather.

I want to add the two columns into one and also add the columns' name into the rows. I want also the columns names to be in bold.

Expected outcome:

             Joined_columns()
0   ID: T1002.  Parent: Stay home.   Child: 2Severe weather.
1   ID: T5006.  Parent: Stay home.   Child: 5847.
2   ID: T5007.  Parent: Stay home.   Child: Severe weather.

The join is accomplished with the following code:

df1_final=df1.stack().groupby(level=0).apply(' '.join).to_frame(0)

But I am not sure how to go to the end. Any ideas

1 Answers

Try this :

col_= df.columns[0]
col_list = list(df.columns)
col_list.remove(col_)
[ col_ := col_+'_'+ col for col in col_list ]

df = pd.DataFrame(df.stack(level=0))
df.reset_index(inplace=True)
df[col_] = df['level_1']+ ' : ' + df[0].astype(str) + ' '
df = df[['level_0',col_]]
df = df.groupby('level_0').sum()
df.reset_index(inplace=True,drop=True)
Related