2

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'
]
ebosi
  • 1,285
  • 5
  • 17
  • 37
  • You mean `(df.name+' ate '+df.qty.astype(str)+' '+df.fruit).tolist()` ? – anky May 01 '19 at 09:45
  • @anky_91 Yes, you are right. I also think that your answer is better than the others provided, as it avoids a for-loop, and is more (imho) pythonic. Would you mind transforming your comment as an answer? – ebosi May 02 '19 at 11:45
  • Okay, i added it. – anky May 02 '19 at 11:53
  • @ebosi Sorry, but why in accepting answer is no f string? Because your question clearly state need f strings for solution, no need any solution with expected output. – jezrael May 04 '19 at 08:00
  • @jezrael you are right: with the initial phrasing of my question (i.e. at the time you wrote your answer and, later, your comment), the accepted answer wasn't answering _the question_ itself, but rather _the issue I was facing_. I believe that anky_91's answer is more "pythonic", as it's a one-liner without a for-loop… and thus, more appropriate as "accepted answer". I've appreciated your answer, though. But I understand you could be frustrated as I've realized I was facing a XY problem only after you spent time helping me. – ebosi May 04 '19 at 14:30
  • @ebosi Ya, exactly. unfortunately it means answer is closed as dupe. – jezrael May 04 '19 at 20:27
  • @jezrael even better! thanks for the tidy up! – ebosi May 04 '19 at 21:00

3 Answers3

6

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]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

Use

pandas.apply:

df.apply(lambda x: x['name'] + " ate " + str(x['qty']) + " " + x['fruit'],1).values
hacker315
  • 1,996
  • 2
  • 13
  • 23
1

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']
anky
  • 74,114
  • 11
  • 41
  • 70