3

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
  • Your solution seems elegant enough in my opinion, and it already uses f-strings, trying to use team1 instead of df['team1'] will complexify the code. Commented Feb 10, 2021 at 10:02

1 Answer 1

1

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)  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.