総まとめ (2)
ときどき、関数の呼び出しでミスをしてしまいます。自分で作った関数でも同じです。でも心配はいりません!この演習では、前の章で作成した count_entries() 関数に try-except ブロックを追加して改良します。これにより、ユーザーが count_entries() を呼び出したときに、指定した列名が DataFrame に存在しない場合でも、役立つメッセージを表示できるようになります。
今回も便宜上、pandas は pd としてインポート済みで、'tweets.csv' は DataFrame の tweets_df に読み込まれています。前回の作業の一部コードも用意してあります。
この演習はコースの一部です
Pythonの関数入門
演習の手順
- 正しい引数で関数が呼び出されたときに、DataFrame を処理して結果の辞書を返すよう、
tryブロックを追加してください。 - 関数が誤って呼び出されたときに、次のエラーメッセージを表示するよう
exceptブロックを追加してください:'The DataFrame does not have a ' + col_name + ' column.'.
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Define count_entries()
def count_entries(df, col_name='lang'):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: cols_count
cols_count = {}
# Add try block
____:
# 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
# Add except block
____:
____
# Call count_entries(): result1
result1 = count_entries(tweets_df, 'lang')
# Print result1
print(result1)