始める無料で始める

総まとめ (3)

前の演習では、関数 count_entries()try-except ブロックを追加しました。これは、存在しない列名を渡して count_entries() を呼び出したユーザーに、役立つメッセージを返すためでした。今回は、ユーザーが DataFrame に存在しない列名を指定した場合に、ValueError を送出するようにします。

今回も便宜上、pandaspd としてインポート済みで、'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)
コードを編集して実行