Exercise

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.

Instructions 1/3

undefined XP
    1
    2
    3
  • Update the function compute_ratio to take a list of numerator column names and sum them up so that one value is returned for each row; do the same for a list of denominator column names.