開始使用免費開始

綜合練習(2)

太棒了!你剛把上一章做的 Twitter 語言分析泛化了,為欄位名稱加入了預設參數。接下來要再更進一步,讓使用者可以傳入彈性的參數數量;在這個情境下,就是讓使用者想傳幾個欄位名稱都可以!

為了方便你練習,pandas 已匯入為 pd,而 'tweets.csv' 也已匯入到 DataFrame tweets_df。前一個練習的部分程式碼也已提供。

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 在函式標頭中補上 DataFrame df 的參數,以及彈性參數 *args
  • 在函式定義中完成 for 迴圈,讓迴圈能遍歷元組 args
  • 呼叫 count_entries(),傳入 DataFrame tweets_df 與欄位名稱 'lang'。將結果指定給 result1
  • 呼叫 count_entries(),傳入 DataFrame tweets_df 與欄位名稱 'lang''source'。將結果指定給 result2

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define count_entries()
def ____(____, ____):
    """Return a dictionary with counts of
    occurrences as value for each key."""
    
    #Initialize an empty dictionary: cols_count
    cols_count = {}
    
    # Iterate over column names in args
    for col_name in ____:
    
        # 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 = count_entries(____, ____)

# Call count_entries(): result2
result2 = count_entries(____, ____, ____)

# Print result1 and result2
print(result1)
print(result2)
編輯並執行程式碼