f-strings with variable number of parameters?

375 views Asked by At

I need to create messages of the kind Hi John, it's time to eat quantity_1 of food1, quantity_2 of food_2 ..., qunatity_n of food_n. For that I get pandas dataframes, that update every once in a while. For example the dataframes look sometimes like df1=

qantity,food
1,apple

and sometimes like df2=

quantity,food
1,apple
3,salads
2,carrots

I need with every new update to create out of the dataframe a string for a message. For df1 an f-string works neetly and for creating my desired message of Hi John, it's time to eat 1 apple. I can do:

f"Hi John, it's time to eat {df.quantity} {df1.food}

In the cases when I have something like df2, and I don't know explicitly how long df2 is, I would like to have a message of the kind Hi John, it's time to eat 1 apple, 3 salads, 2 carrots.

How can I create such a string? I thought of using the "splat" operator for something like join(*zip(df.quantity, df.food)), but I haven't figured it out. tnx

5

There are 5 answers

5
IoaTzimas On BEST ANSWER

Try this:

result=','.join([str(i[0])+' '+i[1] for i in zip(df.quantity, df.food)])

print(result)

'1 apple, 2 salads, 3 carrots'

And you can add this to get the final result:

"Hi John, it's time to eat " + result

Hi John, it's time to eat 1 apple, 2 salads, 3 carrots
2
Concorde On

There are two ways to approach this. The first option is to create a message column in the dataframe

df = pd.DataFrame(data={'quantity':  [1],'food': ['apple']})
df['message'] = df.apply(lambda x: f"Hi John, it's time to eat {x.quantity} {x.food}", axis = 1)
print(df['message'])

the second option is to get slice the dataframe object by index to create your messages outside of the dataframe

f"Hi John, it's time to eat {df.quantity[0]} {df.food[0]}"

to handle multiple records in the dataframe, you can iterate through the rows

"Hi John, it's time to eat " + ", ".join(list((f"{df.quantity[i]} {df.food[i]}" for i in df.index)))
3
Siva Kumar Sunku On

Try this

df1 = pd.DataFrame({'size':['1','2'], 'Food':['apple', 'banana']})
l_1 = [x + '' + y for x, y in zip(df1['size'], df1['Food'])]
"Hi John, it's time to eat " + ", ".join(l_1)
6
buran On
import pandas as pd 
df = pd.DataFrame([[1, 'apple'], [2, 'salads'], [5, 'carrots']], columns=['quantity','food'])
menu =  ', '.join(f"{quantity} {food}" for idx, (quantity, food) in df.iterrows())
print(f"Hi John, it's time to eat {menu}.")

output

Hi John, it's time to eat 1 apple, 2 salads, 5 carrots.

using package inflect you can do it with better grammar:

import inflect

p=inflect.engine()
menu = p.join([f"{quantity} {food}" for idx, (quantity, food) in df.iterrows()])
print(f"Hi John, it's time to eat {menu}.")

output:

Hi John, it's time to eat 1 apple, 2 salads, and 5 carrots.

inflect even can construct correct singular/plural form

0
newbie_coder On

I prefer to use str.format() for complex scenarios as it makes the code easier to read.

In this case:

import pandas as pd
df2=pd.DataFrame({'quantity':[1,3,2],'food':['apple','salads','carrots']})
def create_advice(df):
    s="Hi John, it's time to eat "+", ".join(['{} {}'.format(row['quantity'],row['food']) for index,row in df.iterrows()])+'.'
    return s

create_advice(df2)
>"Hi John, it's time to eat 1 apple, 3 salads, 2 carrots."

You might also want to modify the df slightly before creating the strings:

list_of_portioned_food=['salads']
df2['food']=df2.apply(lambda row: ('portions of ' if row['food'] in list_of_portioned_food else '')+row['food'],axis=1)
df2.iloc[len(df2)-1,1]='and '+str(df2.iloc[len(df2)-1,1])

applying the above function again:

create_advice(df2)
> "Hi John, it's time to eat 1 apple, 3 portions of salads, and 2 carrots."