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'
]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With