기본 인수에 대한 모범 사례
당신의 동료(분명 이 과정을 듣지 않았겠죠)가 pandas DataFrame에 열을 추가하는 함수를 작성했습니다. 안타깝게도 기본 인수 값으로 변경 가능한 변수를 사용했네요! 예기치 않은 동작이 발생하지 않도록, 더 나은 방법을 보여 주세요.
def add_column(values, df=pandas.DataFrame()):
"""DataFrame `df`에 `values`로 이루어진 열을 추가합니다.
열 이름은 "n"이 열의 숫자 인덱스일 때 "col_<n>" 형식이 됩니다.
Args:
values (iterable): 새 열의 값
df (DataFrame, optional): 업데이트할 DataFrame.
DataFrame을 전달하지 않으면 기본으로 하나를 생성합니다.
Returns:
DataFrame
"""
df['col_{}'.format(len(df.columns))] = values
return df
이 연습은 강의의 일부입니다
Python으로 함수 작성하기
연습 안내
- 모범 사례를 따르도록
df의 기본값을 변경 불가능한 값으로 바꾸세요. - 호출자가 DataFrame을 전달하지 않은 경우 새 DataFrame이 생성되도록 함수 코드를 수정하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# 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