How can we use a pandas dataframe column in string formating

Viewed 55

Don't know how to ask. Want add the row values in a string using formating.like If I have a df like below:

things qty place
Apple 1 Table
Mango 4 Chair
Coke 3 Floor
Pen 2 Table

I want output like below:

things qty place string
Apple 1 Table 1 Apple on the Table
Mango 4 Chair 4 Mango on the Chair
Coke 3 Floor 3 Coke on the Floor
Pen 2 Table 2 Pen on the Table

I'm using df['string'] = f'{df['qty']} {df['things']} on the {df['place']}' but not getting the exact.

3 Answers

Just use :-

df['string']=df['qty'].astype(str)+' '+df['things']+' on the '+df['place']
  1. Convert the dataframe into a dictionary.

  2. Add the new data column to the dictionary in the same format.

  3. Convert the dictionary back to a dataframe

    data_dict = df.to_dict()

    data_dict["string"] = ["1 Apple on the Table"......]

    pd.Dataframe.from_dict(data_dict)

Here's an article which might be of help: https://re-thought.com/how-to-add-new-columns-in-a-dataframe-in-pandas/

You can use pd.Series.str.cat here.

df["qty"].astype(str).str.cat(
    [df["things"], ("on the " + df["place"])], sep=" "
)

0    1 Apple on the Table
1    4 Mango on the Chair
2     3 Coke on the Floor
3      2 Pen on the Table
Name: qty, dtype: object

If you want to use f-string then you can use df.apply over axis 1(but this approach is slow and should be used as last resort).

df.apply(lambda x: f'{x.qty} {x.things} on the {x.place}', axis=1)
Related