簡單使用 .apply()
來動手練習一下 .apply()!
你拿到完整的 scores 資料集,其中包含學生的表現以及背景資訊。
你的任務是定義 prevalence() 函式,並將它套用到 scores DataFrame 中 groups_to_consider 指定的欄位。這個函式應該回傳給定欄位中最常見的群組/類別(例如:如果 lunch 欄位中最常見的類別是 standard,則 prevalence() 應回傳 standard)。
functools 模組中的 reduce() 函式已經匯入。
提示:pd.Series 是可疊代(Iterable)物件,因此你可以對它使用標準的操作。
本練習屬於課程
Python 程式面試題實作練習
練習說明
- 以傳入的物件
series為基礎,建立一個包含唯一項目及其計數的元組清單。 - 使用
reduce()萃取出擁有最高計數的那個元組。 - 回傳計數最高的那個項目。
- 將
prevalence函式套用到scoresDataFrame 的groups_to_consider指定欄位上。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def prevalence(series):
vals = list(series)
# Create a tuple list with unique items and their counts
itms = [(____, ____) for x in set(____)]
# Extract a tuple with the highest counts using reduce()
res = reduce(lambda x, y: ____, ____)
# Return the item with the highest counts
return ____[____]
# Apply the prevalence function on the scores DataFrame
result = scores[groups_to_consider].____
print(result)