เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

แนวปฏิบัติที่ดีสำหรับอาร์กิวเมนต์ค่าเริ่มต้น

เพื่อนร่วมงานของคุณ (ที่เห็นได้ชัดว่ายังไม่ได้เรียนคอร์สนี้) เขียนฟังก์ชันนี้ขึ้นมาเพื่อเพิ่มคอลัมน์ให้กับ DataFrame ของ pandas น่าเสียดายที่เขาใช้ตัวแปรแบบ 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

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เปลี่ยนค่าเริ่มต้นของ df ให้เป็นค่าแบบ 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
แก้ไขและรันโค้ด