How to create new column in function using f-string in Pandas Python?

Question:

I have line of my code in Python Pandas like below, but it is not correct I assume:

def xxx(df, dates, date1):
    for col in dates:
        df[f"{col} + _name"] = (df["{date1}"] - df["{col}"]).dt.days

I try to run a loop by all "col" from "dates" list and by doing so create new columns with the same name as input "col" but add suffix "_name", for example:

I have column with name XXX and a need to create new with name XXX_name, how to do that in f string ?

How to do that in Python Pandas ?, please modify my code 🙂

Asked By: dingaro

||

Answers:

With f-string you don’t need to include the "plus" symbol. Just type what you think the string should look like with the brackets. Also, remove the {} brackets from your other column names (date1 and col) and just have them in quotes like df["date"] and df["col"]

~~ Some example code to see the type of formatting you should follow:

value = [1,2,3,4,5]
names = ["1", "2", "3", "4", "5"]

df = pd.DataFrame({"names":names, "value":value})
for col in df.columns:
    df[f"{col}_name"] = [float(x) for x in values]
    df[f"{col}_new"] = df["names"] + df["value"].astype(str)
Answered By: Michael S.

In relation to Jul 31 2022 post by Michael S. Change the name of the list to "values", instead of "value". Also, in the 3rd line: … "value":values

Answered By: Emmanuel Yashchin