Search code examples
pythonpandasfunctiondatef-string

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


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 :)


Solution

  • 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)