Search code examples
pythonpandasdataframef-string

How to create list of f-string (alike) based on pd.DataFrame values?


Problem
How to create a list of strings with placeholders (i.e., "f-string"-like) based on values of a pandas DataFrame?

Example

Imagine I have following dataframe:

import pandas as pd

data = [
    ['Alice', 13, 'apples'],
    ['Bob', 17, 'bananas']
]

df = pd.DataFrame(
    data,
    columns=['name', 'qty', 'fruit']
)

How to create a list of strings using something like f"{name} ate {qty} {fruit}" as a pattern?
In other words, how to create following list:

[
    'Alice ate 13 apples',
    'Bob ate 17 bananas'
]

Solution

  • Putting this to an answer, we can combine the columns and call .tolist() at the end:

    (df.name+' ate '+df.qty.astype(str)+' '+df.fruit).tolist()
    

    Output:

    ['Alice ate 13 apples', 'Bob ate 17 bananas']