始める無料で始める

総仕上げ (1)

前の章の「総仕上げ」の演習を思い出してください。特定の言語のツイート数を数える関数を作成し、簡単なTwitter解析を行いました。関数の出力は、言語がキー、各言語のツイート数が値になっている辞書でした。

この演習では、前の章で行ったTwitterの言語解析を一般化します。具体的には、列名を受け取るデフォルト引数を含めます。

便宜上、pandaspd としてインポート済みで、'tweets.csv' は DataFrame tweets_df に読み込まれています。前回のコードの一部も用意されています。

この演習はコースの一部です

Pythonの関数入門

コースを見る

演習の手順

  • 関数ヘッダーを完成させてください。DataFrame 用のパラメータ df と、DataFrame の列名を表すパラメータ col_name(デフォルト値は 'lang')を指定します。
  • DataFrame tweets_df と列名 'lang' を渡して count_entries() を呼び出し、結果を result1 に代入します。'lang'col_name のデフォルト値なので、ここでは省略しても構いません。
  • DataFrame tweets_df と列名 'source' を渡して count_entries() を呼び出し、結果を 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)
コードを編集して実行