Bringing it all together (3)
पिछले अभ्यास में, आपने अपने count_entries() फंक्शन में एक try-except ब्लॉक जोड़ा था. इससे यह सुनिश्चित हुआ कि जब कोई उपयोगकर्ता आपके count_entries() फंक्शन को कॉल करे और ऐसा कॉलम नाम दे जो DataFrame में मौजूद नहीं है, तो उसे सहायक संदेश मिले. इस अभ्यास में, अगर उपयोगकर्ता ऐसा कॉलम नाम देता है जो DataFrame में नहीं है, तो आप इसके बजाय एक ValueError उठाएँगे.
आपकी सुविधा के लिए, pandas को pd नाम से इम्पोर्ट कर लिया गया है और 'tweets.csv' फाइल को DataFrame tweets_df में लोड किया गया है. आपके पिछले काम के कुछ हिस्से भी दिए गए हैं.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Functions का परिचय
अभ्यास निर्देश
- अगर
col_name, DataFramedfका कॉलम नहीं है, तो एकValueError 'The DataFrame does not have a ' + col_name + ' column.'उठाएँ. - अपने नए फंक्शन
count_entries()कोtweets_dfके'lang'कॉलम का विश्लेषण करने के लिए कॉल करें. नतीजाresult1में स्टोर करें. result1को प्रिंट करें. यह आपके लिए किया जा चुका है, इसलिए परिणाम देखने के लिए 'उत्तर सबमिट करें' पर क्लिक करें. अगले अभ्यास में, आप देखेंगे कि यह ज़रूरीValueErrorsउठाता है.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Define count_entries()
def count_entries(df, col_name='lang'):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Raise a ValueError if col_name is NOT in DataFrame
if col_name not in df.columns:
____
# 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
____
# Print result1
print(result1)