Začněte nyníZačněte zdarma

Správný přístup k výchozím argumentům

Tvůj kolega (který tento kurz zjevně neabsolvoval) napsal funkci pro přidání sloupce do pandas DataFrame. Bohužel jako výchozí hodnotu argumentu použil proměnlivou proměnnou! Ukaž mu lepší způsob, jak to udělat, aby se vyhnul nečekanému chová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

Toto cvičení je součástí kurzu

Writing Functions in Python

Zobrazit kurz

Pokyny k cvičení

  • Změň výchozí hodnotu parametru df na neměnitelnou hodnotu, aby kód odpovídal osvědčeným postupům.
  • Uprav kód funkce tak, aby se nový DataFrame vytvořil v případě, že ho volající nepředal.

Interaktivní cvičení na vyzkoušení si v praxi

Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.

# 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
Upravit a spustit kód