開始使用免費開始

更新自訂函式以執行減法

你在前一個練習撰寫的函式無法執行減法。請看看這個函式:

def compute_ratio(df, numerator, denominator, ratio_name, 
                  addition_in_numerator = True,
                  addition_in_denominator = True):
  numerator_of_ratio = np.where(addition_in_numerator,
                             df[numerator].sum(axis=1), 
                             df[numerator[0]] - df[numerator[1:]].sum(
                               axis=1))
  denominator_of_ratio = np.where(addition_in_denominator, 
                               df[denominator].sum(axis=1), 
                               df[denominator[0]] - df[denominator[1:]].sum(axis=1))
  df[ratio_name] = numerator_of_ratio/denominator_of_ratio
  return df

這個函式可以處理財務比率中分子與分母的加法與減法。請注意,函式使用了 np.where。這是 NumPy 套件中的函式。np.where 會檢查第一個引數是否為 True;若是,回傳第二個引數,否則回傳第三個引數。例如,上述程式碼中有:

np.where(addition_in_numerator,
                             df[numerator].sum(axis=1), 
                             df[numerator[0]] - df[numerator[1:]].sum(
                               axis=1))

如果 addition_in_numerator 為 true,np.where 會回傳 df[numerator].sum(axis=1),否則會回傳 df[numerator[0]] - df[numerator[1:]].sum(axis=1)

在本練習中,balance_sheet DataFrame 以及 pandas 和 NumPy(分別為 pdnp)都已為你載入。請使用這些資源判斷下列哪個敘述是正確的。

本練習屬於課程

使用 Python 分析財務報表

檢視課程

動手互動練習

將理論付諸實踐,立即體驗我們的互動練習

開始練習