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
CodePudding user response:
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)