1. Учиться
  2. /
  3. Courses
  4. /
  5. Python関数の書き方

Connected

Exercise

デフォルト引数のベストプラクティス

同僚(このコースを受けていないのは明らかですね)が、pandas の DataFrame に列を追加する関数を書きました。ところが、デフォルト引数にミュータブルな変数を使ってしまっています!予期せぬ動作を避けられるように、より良い書き方を教えてあげましょう。

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

Инструкции

100 XP
  • ベストプラクティスに従い、df のデフォルト値をイミュータブルな値に変更してください。
  • 呼び出し側が DataFrame を渡さなかった場合は新しい DataFrame を作成するよう、関数のコードを更新してください。