Populate predefined string with dataframe values in Python?

Viewed 33

I have a string that should look like this: "On 2021-02-08, Buccaneers won against Chiefs in the Super Bowl. MVP was Tom Brady."

Or, with placeholders,like this: "On [date], [team1] [won/lost] against [team2]. MVP was [mvp]"

With a dataframe looking like

date          team1         team2     won    mvp
2021-02-08    Buccaneers    Chiefs    won    Tom Brady

Imagine the dataframe populated with all the super bowls. Now, I would like to have a final column "printString", that inserts the previous columns in the appropriate position. I could do that with

df["printString"] = f'On {df["date"]}, {df["team1"]} {df["won"]} against {df["team2"]} in the Super Bowl. MVP was {df["mvp"]}'

Is there a more elegant solution to this? Possibly something where I could write {team1} instead of df["team1"}?

1 Answers

Use DataFrame.apply here:

func = lambda x: f'On {x["date"]}, {x["team1"]} {x["won"]} against {x["team2"]} in the Super Bowl. MVP was {x["mvp"]}'
df["printString"] = df.apply(func, axis=1)  
Related