総まとめ (2)
前の章で行ったTwitterの言語分析を一般化し、列名にデフォルト引数を追加できましたね。ここからもう一歩進めて、この関数に柔軟な引数を渡せるようにします。つまり、この場合はユーザーが望むだけ多くの列名を指定できるようにします!
今回も便宜上、pandas は pd としてインポート済みで、'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)