Updating the user-defined function
User-defined functions are a great way of reducing repetitive work. The function defined in the video is provided below:
def compute_ratio(df, numerator, denominator,
ratio_name):
df[ratio_name] = df[numerator] / df[denominator]
return df
Notice that the function we defined cannot directly compute ratios that require adding or subtracting values in the numerator and denominator, such as the operating or the gross margin ratio.
In this exercise, you will update this function so that it can be used to compute ratios that involve addition in the numerator and denominator.
You will use a pandas function called .sum()
, which can sum over an axis in the DataFrame. An axis of 0 means rows, so it would sum up values over the rows and return one value for each column. An axis of 1 means columns, so it would sum up values from different columns in df
and return one value for each row. You can think of df.sum(axis=1)
as being equivalent to df[column_1] + ... + df[column_n]
. The default axis in pd.sum()
is 0.
Diese Übung ist Teil des Kurses
Analyzing Financial Statements in Python
Interaktive Übung
Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.
# Update the function
def compute_ratio(df, numerator, denominator, ratio_name):
df[ratio_name] = df[numerator]____ / df[denominator]____
return df