開始使用免費開始

抽取一個函式

在開發預測大學畢業與否的模型時,你寫了下列程式碼來計算學生每年 GPA 的 z 分數(z 分數表示與平均值的標準差距離)。現在你準備把它變成可上線的系統,因此需要處理重複的程式碼。寫一個用來計算 z 分數的函式會讓程式更好。

# Standardize the GPAs for each year
df['y1_z'] = (df.y1_gpa - df.y1_gpa.mean()) / df.y1_gpa.std()
df['y2_z'] = (df.y2_gpa - df.y2_gpa.mean()) / df.y2_gpa.std()
df['y3_z'] = (df.y3_gpa - df.y3_gpa.mean()) / df.y3_gpa.std()
df['y4_z'] = (df.y4_gpa - df.y4_gpa.mean()) / df.y4_gpa.std()

注意:df 是一個 pandas 的 DataFrame,每列代表一位學生,包含 4 個年度 GPA 欄位:y1_gpay2_gpay3_gpay4_gpa

本練習屬於課程

Python 函式寫作

檢視課程

練習說明

  • 完成函式,讓它回傳某一欄位的 z 分數。
  • 使用該函式,從原始 GPA 分數(df.y1_gpadf.y2_gpa 等)計算每一年的 z 分數(df['y1_z']df['y2_z'] 等)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def standardize(column):
  """Standardize the values in a column.

  Args:
    column (pandas Series): The data to standardize.

  Returns:
    pandas Series: the values as z-scores
  """
  # Finish the function so that it returns the z-scores
  z_score = (____ - ____.____()) / ____.____()
  return z_score

# Use the standardize() function to calculate the z-scores
df['y1_z'] = ____
df['y2_z'] = ____
df['y3_z'] = ____
df['y4_z'] = ____
編輯並執行程式碼