始める無料で始める

総まとめ (2)

前の章で行ったTwitterの言語分析を一般化し、列名にデフォルト引数を追加できましたね。ここからもう一歩進めて、この関数に柔軟な引数を渡せるようにします。つまり、この場合はユーザーが望むだけ多くの列名を指定できるようにします!

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

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

Pythonの関数入門

コースを見る

演習の手順

  • 関数ヘッダーを完成させ、DataFrame 用のパラメータ df と柔軟な引数 *args を指定します。
  • 関数定義内の for ループを完成させ、タプル args を繰り返し処理するようにします。
  • DataFrame tweets_df と列名 'lang' を渡して count_entries() を呼び出し、結果を result1 に代入します。
  • DataFrame tweets_df と列名 'lang''source' を渡して count_entries() を呼び出し、結果を 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)
コードを編集して実行