शुरू करेंमुफ़्त में शुरू करें

Default arguments के लिए Best practice

आपके एक सहकर्मी (जिन्होंने स्पष्ट रूप से यह कोर्स नहीं किया) ने pandas DataFrame में एक कॉलम जोड़ने के लिए यह फंक्शन लिखा है. दुर्भाग्य से, उन्होंने default argument के रूप में एक mutable वैरिएबल इस्तेमाल कर लिया! कृपया उन्हें इसका बेहतर तरीका दिखाइए ताकि उन्हें अनपेक्षित व्यवहार न मिले.

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

यह अभ्यास पाठ्यक्रम का हिस्सा है

Python में Functions लिखना

पाठ्यक्रम देखें

अभ्यास निर्देश

  • best practices के अनुसार df की default वैल्यू को किसी immutable वैल्यू में बदलें.
  • फंक्शन के कोड को अपडेट करें ताकि अगर कॉलर कोई 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
कोड संपादित करें और चलाएँ