Cập nhật hàm do bạn định nghĩa để thực hiện phép trừ
Hàm bạn đã làm ở bài tập trước không thể thực hiện phép trừ. Hãy xem hàm này:
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
Hàm này có thể xử lý cả phép cộng và phép trừ trong tử số và mẫu số của các tỷ số tài chính. Lưu ý rằng hàm sử dụng np.where. Đây là một hàm từ gói NumPy. np.where kiểm tra xem đối số đầu tiên có phải là True không; nếu đúng, nó trả về đối số thứ hai, nếu không thì trả về đối số thứ ba. Ví dụ, ở trên ta có:
np.where(addition_in_numerator,
df[numerator].sum(axis=1),
df[numerator[0]] - df[numerator[1:]].sum(
axis=1))
Nếu addition_in_numerator là true, np.where sẽ trả về df[numerator].sum(axis=1), còn nếu không, nó sẽ trả về df[numerator[0]] - df[numerator[1:]].sum(axis=1).
Trong bài tập này, DataFrame balance_sheet, cùng với pandas và NumPy lần lượt là pd và np, đã được nạp sẵn cho bạn. Hãy dùng chúng để xác định phát biểu nào dưới đây là đúng.
Bài tập này là một phần của khóa học
Phân tích báo cáo tài chính bằng Python
Bài tập tương tác thực hành
Biến lý thuyết thành hành động với một trong các bài tập tương tác của chúng tôi
Bắt đầu bài tập