我需要创建类似的消息
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))
之类的操作,但我还没有弄清楚。 tnx
试试这个:
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
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.
变形甚至可以构造正确的单数/复数形式
有两种方法可以解决这个问题。 第一个选项是在数据框中创建消息列
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)))
对于复杂的场景,我更喜欢使用 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."
试试这个
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)
我实际上在我的项目中使用了 SQLite3,但解决方案仍然有效:您可以创建一个串联函数,循环遍历参数,将它们附加到字符串,并将生成的完整字符串插入到另一个 f 字符串中。
def concat_String(values):
str = ""
for v in values:
str += f" {v}"
def create_New_Table(con, cur, table_name, values):
try:
cur.execute(f"CREATE TABLE {table_name}({concat_String(values)})")