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

Creating Message column from dataframe in Pandas

a little help here. So I am trying to create a msg column to utilise some information in the other columns. I have tried some few methods but I seem to be missing out on something. so this is a simulation

df
Name A B C
Jane 1 2 3
Celi 4 5 9

df[msg]=(f'''Hi {df.Name} you have {df.A} for A and {df.B} for B, making {df.C} in total for {(datetime.date.today()) - datetime.timedelta(days=7)} and {(datetime.date.today())}. ''')

expected output for first row

Hi Jane you have 1 for A and 2 for B, making 3 in total for 2022-09-25 to 2022-10-01

df
Name A B C msg
Jane 1 2 3  Hi Jane you have 1 for A and 2 for B, making 3 in total for 2022-09-25 to 2022-10-01
Celi 4 5 9  Hi Jane you have 1 for A and 2 for B, making 3 in total for 2022-09-25 to 2022-10-01

anything I could do to replicate for each row independently? As it produces all the names and info in one column

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 :

I’d suggest moving your message-maker into its own function and applying this function to every row in your dataframe:

import datetime
import pandas as pd

def make_message(row):
    datetime_today = datetime.date.today()
    return f'Hi {row.Name} you have {row.A} for A and {row.B} for B, making {row.C} in total for {datetime_today - datetime.timedelta(days=7)} and {datetime_today}.'

df = pd.DataFrame([['Jane', 1, 2, 3], ['Celi', 4, 5, 6]], columns=['Name', 'A', 'B', 'C'])
df['msg'] = df.apply(lambda row : make_message(row), axis=1)
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