整合所學(2)
做得好!你現在已經完成能在欄位中逐一走訪每個項目,並建立一個字典,其鍵為語言名稱、其值為該語言的推文數量的功能。
在這個練習中,你會把前一題做出的功能封裝成一個函式,從函式內回傳產生的字典,並用正確的引數來呼叫這個函式。
為了方便你作答,已經將 pandas 套件匯入為 pd,並把 'tweets.csv' 檔案讀入變數 tweets_df。
本練習屬於課程
Python 函式入門
練習說明
- 定義函式
count_entries(),包含兩個參數。第一個參數df代表 DataFrame,第二個參數col_name代表欄位名稱。 - 在
for迴圈中的if-else敘述填入內容:如果鍵已存在於字典langs_count,就在其目前值上加1;否則將該鍵加入langs_count,並把其值設為1。在程式中使用迴圈變數entry。 - 從
count_entries()函式內回傳langs_count字典。 - 呼叫
count_entries(),將tweets_df與欄位名稱'lang'傳入,並把回傳結果指定給變數result。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define count_entries()
def ____(____, ____):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: langs_count
langs_count = {}
# Extract column from DataFrame: col
col = df[col_name]
# Iterate over lang column in DataFrame
for entry in col:
# If the language is in langs_count, add 1
if entry in langs_count.keys():
____
# Else add the language to langs_count, set the value to 1
else:
____
# Return the langs_count dictionary
# Call count_entries(): result
# Print the result
print(result)