首页 > 解决方案 > 如何使用字典更新数据框中的一个值?

问题描述

在执行另一个计算之前,我无法根据字典的值更新数据框中的单个值

我正在使用数据框,并希望计算每行不同列中的值。在完成一行的计算后,需要更改之后行中的值,然后才能进行新的计算。这是因为此后行中的值取决于前一行的结果。

为了接近它,我正在使用字典。目前我在 Excel 中工作,我设法用字典更新单个单元格的值。但是,为了使计算更快,我想使用适当的数据框。

我设法根据结果更新字典,但我没有设法用这些新的 citionary 值更新我的数据框

适用于我当前基于 Excel 的模型的代码是:

dict1={1:10,2:15.....38:29}     #my dictionary

for row in range(2,sheet.max_row+1):
  #updates the table with values of the dictionary before each calculation
    sheet['F'+str(row)].value = dict1[sheet['C'+str(row)].value] 
  # calculations being executed
        (.....)
  #updating the dictionary with the results of the calculations in the row
    dict1_1={sheet['C'+str(row)].value :sheet['F'+str(row)].value}
    dict1.update(dict1_1)

到目前为止,我对数据框的尝试如下所示:

 for row in df.T.itertuples():
    df.replace({"P_building_kg_y": dict1}) ##### <-----HERE IS THE PROBLEM!
  # calculations being executed
        (.....)
  #updating the dictionary with the results of the calculations in the row
    dict1_1=dict(zip(df.FacilityID, df.P_building_kg_y))
    dict1.update(dict1_1)

我只想根据字典更新数据框中的值。如果您知道如何做到这一点,我将不胜感激!

标签: python-2.7dataframedictionary

解决方案


推荐阅读