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

f-strings with variable number of parameters?

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

qantity,food
1,apple

有时喜欢df2=

quantity,food
1,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. 的消息

如何创建这样的字符串? 我想过使用“splat”运算符来表示 join(*zip(df.quantity, df.food)) 之类的东西,但我还没有弄明白。发送

试试这个:

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

print(result)

'1 apple, 2 salads, 3 carrots'

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

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

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

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

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]}"

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

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

试试这个

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

使用包 inflect 你可以用更好的语法来做到这一点:

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

输出:

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

变形甚至可以构造正确的singular/plural形式

对于复杂的场景,我更喜欢使用 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, it's time to eat 1 apple, 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, it's time to eat 1 apple, 3 portions of salads, and 2 carrots."