参数数目可变的f字符串?

问题描述

我需要创建Hi John,it's time to eat quantity_1 of food1,quantity_2 of food_2 ...,qunatity_n of food_n.类型的消息,为此我得到了熊猫数据帧,该消息帧每隔一段时间就会更新一次。例如,数据帧有时看起来像df1=

qantity,food
1,apple

有时也像df2=

quantity,apple
3,salads
2,carrots

每次新更新时,我都需要在数据框中为消息创建一个字符串。对于df1,f字符串可以正常工作,并且可以创建所需的Hi John,it's time to eat 1 apple.消息,我可以这样做:

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

如果我有类似df2之类的东西,而我又不明确知道df2有多长,我希望收到类似Hi John,it's time to eat 1 apple,3 salads,2 carrots.这样的消息>

如何创建这样的字符串?我曾想过对join(*zip(df.quantity,df.food))之类的东西使用“ splat”运算符,但是我还没有弄清楚。 tnx

解决方法

尝试一下:

TMyClass.OnEvent

您可以添加它以获得最终结果:

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

print(result)

'1 apple,2 salads,3 carrots'
,

有两种方法可以解决此问题。 第一种选择是在数据框中创建一个消息列

schedule_end_date

第二个选项是按索引对数据框对象进行切片,以在数据框之外创建消息

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'])

要处理数据框中的多个记录,可以遍历行

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

尝试一下

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)
,
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}.")

输出

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

使用软件包inflect,您可以使用更好的语法:

import inflect

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

输出:

Hi John,and 5 carrots.

变形甚至可以构造正确的单数/复数形式

,

对于复杂的情况,我更喜欢使用str.format(),因为它使代码更易于阅读。

在这种情况下:

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,3 salads,2 carrots."

您可能还想在创建字符串之前稍微修改df:

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])

再次应用上述功能:

create_advice(df2)
> "Hi John,3 portions of salads,and 2 carrots."