簡體   English   中英

根據其他行的值替換 dataframe 行中的變量

[英]Substituting variable in a dataframe row based on other row's value

我有一個 dataframe,其中包含 ID、公式和一個從屬 ID 列,我從公式列中提取了 ID。 現在我必須將所有依賴 ID 替換為基於 dataframe 的公式。

我的方法是為每一行運行一個嵌套循環,以使用替換 function 替換公式中的依賴 ID。 循環將停止,直到沒有更多可能的替換。 但是我不知道從哪里開始,也不確定這是否是正確的方法。

我想知道是否有任何 function 可以使過程更容易?

以下是創建當前 dataframe 的代碼:

data = pd.DataFrame({'ID':['A1','A3','B2','C2','D3','E3'],
    'Formula':['C2/500','If B2 >10 then  (B2*D3) + 100 else D3+10','E3/2 +20','E3/2 +20','var_i','var_x'],
    'Dependent ID':['C2','B2, D3','E3','D3, E3', '','']})

以下是我當前 dataframe 的示例和我想要的最終結果。 當前 dataframe: 當前 DF

期望最終結果: 所需的DF

用公式遞歸替換公式中的依賴 ID:

df = pd.DataFrame({'ID':['A1','A3','B2','C2','D3','E3'],
    'Formula':['C2/500','If B2 >10 then  (B2*D3) + 100 else D3+10','E3/2 +20','D3+E3','var_i','var_x'],
    'Dependent ID':['C2','B2,D3','E3','D3,E3', '','']})

def find_formula(formula:str, ids:str):
    #replace all the ids inside formula with the correct formula
    if ids == '':
        return formula
    ids = ids.split(',')
    for x in ids:
        sub_formula = df.loc[df['ID']==x, 'Formula'].values[0]
        sub_id = df.loc[df['ID']==x, 'Dependent ID'].values[0]
        formula = formula.replace(x, find_formula(sub_formula, sub_id))
    return formula

df['new_formula']=df.apply(lambda x: find_formula(x['Formula'], x['Dependent ID']), axis=1)

output:

ID  Formula Dependent ID    new_formula
0   A1  C2/500      C2      var_i+var_x/500
1   A3  If B2 >10 then (B2*D3) + ...    If var_x/2 +20 >10 then (var_x/2 +20*var_i) + ...
2   B2  E3/2 +20    E3      var_x/2 +20
3   C2  D3+E3       D3,E3   var_i+var_x
4   D3  var_i               var_i
5   E3  var_x               var_x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM