統整練習(2)
有時候我們在呼叫函式時會犯錯——即使是你自己寫的函式也一樣。不用擔心!在這個練習中,你會在上一章寫的 count_entries() 基礎上加入 try-except 區塊,進一步改良它。這能讓你的函式在使用者呼叫 count_entries() 時,若提供的欄位名稱不存在於 DataFrame,就回應一段有幫助的訊息。
同樣地,為了方便你作答,已經將 pandas 以 pd 匯入,並把 'tweets.csv' 匯入成為 DataFrame tweets_df。你先前寫過的部分程式碼也已提供。
本練習屬於課程
Python 函式入門
練習說明
- 加入
try區塊:當以正確引數呼叫函式時,處理 DataFrame,並回傳結果的字典。 - 加入
except區塊:當以錯誤方式呼叫函式時,顯示以下錯誤訊息:'The DataFrame does not have a ' + col_name + ' column.'。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define count_entries()
def count_entries(df, col_name='lang'):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: cols_count
cols_count = {}
# Add try block
____:
# Extract column from DataFrame: col
col = df[col_name]
# Iterate over the column in DataFrame
for entry in col:
# If entry is in cols_count, add 1
if entry in cols_count.keys():
cols_count[entry] += 1
# Else add the entry to cols_count, set the value to 1
else:
cols_count[entry] = 1
# Return the cols_count dictionary
return cols_count
# Add except block
____:
____
# Call count_entries(): result1
result1 = count_entries(tweets_df, 'lang')
# Print result1
print(result1)