假设您有一个数据帧:
import pandas as pd
sales = [{'account': 'Jones LLC', 'nuts': 150, 'bolts': 200, 'totalval': 140, 'Cur': 'pesos'},
{'account': 'Alpha Co', 'nuts': 200, 'bolts': 210, 'totalval': 215, 'Cur': 'euros'},
{'account': 'Blue Inc', 'nuts': 50, 'bolts': 90, 'totalval': 95 , 'Cur': 'pounds'}]
mydf = pd.DataFrame(sales)
你想产生一个字符串来庆祝这个月的利润。例如:
"We made 140 pesos from Jones LLC. Wahoo!"
我第一次尝试解决这个问题是使用一个带有占位符的模板字符串,并用逐行的每月数字格式化它。请注意,这些每月的数字是整数,而不是字符串。你知道吗
celebstring = "We made amt Cur from Jones LLC. Woohoo!"
def createpr(inputdf):
for index, row in inputdf.iterrows():
filledstring = celebstring.replace("amt","{0}".format(str(row["totalval"]))).replace('Cur','{0}'.format(str(row['Cur'])))
inputdf['fullstring'] = filledstring
return inputdf
df2 = createpr(mydf)
但是,当您运行此代码时,所有行的“fullstring”字段只填充最后一行的值。数据框如下所示(注意,为了可读性,我删除了两列):
sales = [{'account': 'Jones LLC','totalval': 140, 'Cur': 'pesos', 'fullstring': 'We got an order totaling 95 pounds selling parts wahoo!'},
{'account': 'Alpha Co','totalval': 215, 'Cur': 'euros', 'fullstring': 'We got an order totaling 95 pounds selling parts wahoo!'},
{'account': 'Blue Inc','totalval': 95 , 'Cur': 'pounds','fullstring': 'We got an order totaling 95 pounds selling parts wahoo!'}]
如何让函数根据每行中相应的值来替换这些值?你知道吗
更容易使用
format_map
分配回
对于
dict
,可以使用to_dict
相关问题 更多 >
编程相关推荐