Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to replace the words in description with dataframe from my column and add it to my dataframe

I want to replace the name and age in description with the data in my table.

data = {'name' : ['Max','Jim'],'Age':[32,44],'desc':''}
desc = "My name is <name> and my age is <age>."

Like this,

Output:
    name    Age desc
0   Max 32  My name is Max and my age is 32.
1   Jim 44  My name is Jim and my age is 44.

I have tried using np.where() and regex functions but still not getting expected results.
I’m using python version 3.11.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For a fully programmatic approach, you can use a regex:

import re

data = {'name' : ['Max','Jim'],'Age':[32,44],'desc':''}
desc = "My name is <name> and my age is <age>."

df = pd.DataFrame(data)
df.columns = df.columns.str.lower()

df['desc'] = df.apply(lambda row: re.sub(r'<(\w+)>',
                                         lambda m: str(row[m.group(1)]), desc),
                      axis=1)

Or with a list comprehension (assuming unique indices!):

df['desc'] = [re.sub(r'<(\w+)>', lambda m: str(df.loc[idx, m.group(1)]), desc)
              for idx in df.index]

Output:

  name  age                              desc
0  Max   32  My name is Max and my age is 32.
1  Jim   44  My name is Jim and my age is 44.

Of course a non-programmatic but much more efficient approach would have been:

df['desc'] = "My name is " + df['name'] + " and my age is " + df['age'] + "."
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading