更新用户自定义函数以执行减法
您在上一个练习中编写的函数无法进行减法。请看下面这个函数:
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 会检查第 1 个参数是否为 True;若为真,则返回第 2 个参数,否则返回第 3 个参数。例如,在上面的代码中:
np.where(addition_in_numerator,
df[numerator].sum(axis=1),
df[numerator[0]] - df[numerator[1:]].sum(
axis=1))
如果 addition_in_numerator 为真,np.where 将返回 df[numerator].sum(axis=1),否则将返回 df[numerator[0]] - df[numerator[1:]].sum(axis=1)。
在本练习中,balance_sheet DataFrame 以及 pandas 和 NumPy(分别为 pd 与 np)均已为您加载。请据此判断以下哪一项表述是正确的。
本练习是课程的一部分
