開始使用免費開始

整合所學(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)
編輯並執行程式碼