総仕上げ (1)
前の章の「総仕上げ」の演習を思い出してください。特定の言語のツイート数を数える関数を作成し、簡単なTwitter解析を行いました。関数の出力は、言語がキー、各言語のツイート数が値になっている辞書でした。
この演習では、前の章で行ったTwitterの言語解析を一般化します。具体的には、列名を受け取るデフォルト引数を含めます。
便宜上、pandas は pd としてインポート済みで、'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)