提取一个函数
在开发一个预测大学毕业率的模型时,您编写了下面的代码来计算学生每年 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_gpa、y2_gpa、y3_gpa、y4_gpa。
本练习是课程的一部分
Python 函数编写
练习说明
- 完成该函数,使其返回某一列的 z 分数。
- 使用该函数,从原始 GPA 分数(
df.y1_gpa、df.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'] = ____