Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
]
like image 756
ebosi Avatar asked Dec 21 '25 21:12

ebosi


1 Answers

Use list comprehension with list of dicts by DataFrame.to_dict:

a = [f"{x['name']} ate {x['qty']} {x['fruit']}" for x in df.to_dict('r')]
print (a)
['Alice ate 13 apples', 'Bob ate 17 bananas']

Or:

a = [f"{name} ate {qty} {fruit}" for name, qty, fruit in df[['name','qty','fruit']].values]
like image 193
jezrael Avatar answered Dec 24 '25 10:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!