Thực hành tốt cho đối số mặc định
Một đồng nghiệp của bạn (rõ ràng là chưa học khóa này) đã viết hàm sau để thêm một cột vào pandas DataFrame. Tiếc là họ đã dùng một biến có thể thay đổi làm giá trị mặc định cho đối số! Hãy chỉ cho họ cách làm tốt hơn để tránh hành vi không mong muốn.
def add_column(values, df=pandas.DataFrame()):
"""Add a column of `values` to a DataFrame `df`.
The column will be named "col_<n>" where "n" is
the numerical index of the column.
Args:
values (iterable): The values of the new column
df (DataFrame, optional): The DataFrame to update.
If no DataFrame is passed, one is created by default.
Returns:
DataFrame
"""
df['col_{}'.format(len(df.columns))] = values
return df
Bài tập này là một phần của khóa học
Viết hàm trong Python
Hướng dẫn bài tập
- Đổi giá trị mặc định của
dfthành một giá trị bất biến để tuân theo thực hành tốt. - Cập nhật mã của hàm để tạo một DataFrame mới nếu người gọi không truyền vào.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Use an immutable variable for the default argument
def better_add_column(values, df=____):
"""Add a column of `values` to a DataFrame `df`.
The column will be named "col_" where "n" is
the numerical index of the column.
Args:
values (iterable): The values of the new column
df (DataFrame, optional): The DataFrame to update.
If no DataFrame is passed, one is created by default.
Returns:
DataFrame
"""
# Update the function to create a default DataFrame
if ____ is ____:
df = pandas.DataFrame()
df['col_{}'.format(len(df.columns))] = values
return df