Computing multiple ratios with the user-defined function
Let's have a look at the function you saw in the last two exercises.
def compute_ratio(df, numerator, denominator, ratio_name,
addition_in_numerator = True,
addition_in_denominator = True):
ratio_numerator = np.where(addition_in_numerator,
df[numerator].sum(axis=1),
df[numerator[0]] - df[numerator[1:]].sum(
axis=1))
ratio_denominator = np.where(addition_in_denominator,
df[denominator].sum(axis=1),
df[denominator[0]] - df[denominator[1:]].sum(axis=1))
df[ratio_name] = ratio_numerator/ratio_denominator
return df
Recall that in the previous exercise, we used the function to compute ratios. Still, it was not more efficient nor did it involve less coding to compute the ratios using this function. In this exercise, you'll see how the function can be used to compute many ratios in a loop. This will make computing multiple ratios more efficient and involve less coding.
This exercise is part of the course
Analyzing Financial Statements in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Print the columns
print(merged_dat.____)