整合練習(1)
回想上一章的「整合練習」,你透過撰寫一個函式來做簡單的 Twitter 分析,計算特定語言的推文數量。該函式的輸出是一個字典,語言作為「鍵」,該語言的推文數作為「值」。
在這個練習中,我們要將你在上一章完成的 Twitter 語言分析一般化。你會透過加入一個能接收欄位名稱的「預設引數」來達成。
為了方便你作答,已經將 pandas 以 pd 匯入,而且已把 'tweets.csv' 載入為 DataFrame tweets_df。同時也提供了你先前完成部分的程式碼。
本練習屬於課程
Python 函式入門
練習說明
- 完成函式標頭,加入參數 DataFrame
df,以及 DataFrame 欄位名稱參數col_name,其預設值為'lang'。 - 呼叫
count_entries(),傳入tweets_df這個 DataFrame 與欄位名稱'lang'。將結果指定給result1。注意:因為'lang'是col_name參數的預設值,你其實不必在這裡特別指定。 - 呼叫
count_entries(),傳入tweets_df這個 DataFrame 與欄位名稱'source'。將結果指定給result2。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define count_entries()
def count_entries(____, ____):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: cols_count
cols_count = {}
# 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
# Call count_entries(): result1
result1 = ____
# Call count_entries(): result2
result2 = ____
# Print result1 and result2
print(result1)
print(result2)