開始使用免費開始

綜合應用(3)

在上一個練習中,你在 count_entries() 函式中加入了 try-except 區塊。這樣使用者在呼叫 count_entries() 並提供一個 DataFrame 中不存在的欄位名稱時,就能收到有幫助的訊息。在本練習中,當使用者提供的欄位名稱不在 DataFrame 裡時,你將改為拋出 ValueError

同樣地,為了方便你,pandas 已以 pd 匯入,'tweets.csv' 也已載入到 DataFrame tweets_df。你先前寫過的部分程式碼也一併提供。

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 如果 col_name 不是 DataFrame df 的欄位,拋出 ValueError 'The DataFrame does not have a ' + col_name + ' column.'
  • 呼叫你新的 count_entries() 函式,分析 tweets_df'lang' 欄位。將結果存到 result1
  • 列印 result1。這一步已替你完成,所以按下「Submit Answer」來查看結果。下一個練習中,你會看到它會拋出必要的 ValueError

動手互動練習

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

# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""
    
    # Raise a ValueError if col_name is NOT in DataFrame
    if col_name not in df.columns:
        ____

    # 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
____

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