額外參數
來練習在 .apply() 方法中使用額外參數吧!
你的任務是替 scores 建立兩個新欄位:
mean:數學、閱讀、寫作成績的逐列平均值。rank:依照mean的高低進行分類:- 若平均值 $> 90$,標記為
'high' - 若平均值 \(> 60\) 且 $\leq 90$,標記為
'medium' - 若平均值 $\leq 60$,標記為
'low'
- 若平均值 $> 90$,標記為
為了完成此任務,你需要定義函式 rank。此函式接收一個 Series,並回傳一個包含兩個值的清單:該 Series 的平均值,以及依上述規則得到的字串。
numpy 模組已替你以 np 名稱匯入。
本練習屬於課程
Python 程式面試題實作練習
練習說明
- 計算輸入 Series 的平均值。
- 以清單形式回傳平均值與其等級(rank)。
- 將
rank()的輸出插入為scores的新欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def rank(series):
# Calculate the mean of the input series
mean = ____
# Return the mean and its rank as a list
if ____:
return ____
if ____:
return ____
return ____
# Insert the output of rank() into new columns of scores
cols = ['math score', 'reading score', 'writing score']
scores[['mean', 'rank']] = scores[cols].____
print(scores[['mean', 'rank']].head())