Home > Software engineering >  add dataframes columns names to rows after join procedure
add dataframes columns names to rows after join procedure

Time:09-28

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: (I cannot make bold the columns names ID, etc)

             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

CodePudding user response:

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)

CodePudding user response:

To get the column names, you can use .name:

>>> df1.apply(lambda sr: f'{sr.name}: '   sr).apply(' '.join, axis=1).to_frame('Joined_columns()')

Output:

                                        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.

To make the columns bold depends on what you're using to display them. For example, ** is often used to signify bold in markdown languages and <b>...</b> tags are used in HTML.

>>> print(df1.apply(lambda sr: f'**{sr.name}**: '   sr).apply(' '.join, axis=1).to_string(index=False))

Output:

ID: T1002. Parent: Stay home. Child: 2Severe weather.

ID: T5006. Parent: Stay home. Child: 5847.

ID: T5007. Parent: Stay home. Child: Severe weather.

or

>>> print(df1.apply(lambda sr: f'<b>{sr.name}</b>: '   sr).apply(' '.join, axis=1).to_string(index=False))

Output:

ID: T1002. Parent: Stay home. Child: 2Severe weather.
ID: T5006. Parent: Stay home. Child: 5847.
ID: T5007. Parent: Stay home. Child: Severe weather.
  • Related