[英]How to populate row of pandas dataframe based on previous row and column condition?
[英]Use column values in Pandas DataFrame to populate string row by row
假設您有一個數據框:
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
更容易
In [40]: mydf.apply('We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1)
Out[40]:
0 We made 140 pesos from Jones LLC. Woohoo!
1 We made 215 pesos from Alpha Co. Woohoo!
2 We made 95 pesos from Blue Inc. Woohoo!
dtype: object
分配給
In [46]: mydf.assign(fullstring=mydf.apply(
'We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1))
Out[46]:
Cur account bolts nuts totalval \
0 pesos Jones LLC 200 150 140
1 euros Alpha Co 210 200 215
2 pounds Blue Inc 90 50 95
fullstring
0 We made 140 pesos from Jones LLC. Woohoo!
1 We made 215 pesos from Alpha Co. Woohoo!
2 We made 95 pesos from Blue Inc. Woohoo!
對於dict
您可以使用to_dict
In [48]: mydf.assign(fullstring=mydf.apply(
'We made {totalval} pesos from {account}. Woohoo!'.format_map, axis=1)
).to_dict(orient='r')
Out[48]:
[{'Cur': 'pesos',
'account': 'Jones LLC',
'bolts': 200,
'nuts': 150,
'totalval': 140,
'fullstring': 'We made 140 pesos from Jones LLC. Woohoo!'},
{'Cur': 'euros',
'account': 'Alpha Co',
'bolts': 210,
'nuts': 200,
'totalval': 215,
'fullstring': 'We made 215 pesos from Alpha Co. Woohoo!'},
{'Cur': 'pounds',
'account': 'Blue Inc',
'bolts': 90,
'nuts': 50,
'totalval': 95,
'fullstring': 'We made 95 pesos from Blue Inc. Woohoo!'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.