รวมทุกอย่างเข้าด้วยกัน (2)
บางครั้งเราอาจเรียกใช้ฟังก์ชันผิดพลาดได้ แม้แต่ฟังก์ชันที่เขียนเองก็ตาม ไม่ต้องกังวล! ในแบบฝึกหัดนี้ จะได้ปรับปรุงฟังก์ชัน count_entries() จากบทที่แล้วโดยเพิ่มบล็อก try-except เข้าไป ซึ่งจะช่วยให้ฟังก์ชันแสดงข้อความที่เป็นประโยชน์เมื่อผู้ใช้ระบุชื่อคอลัมน์ที่ไม่มีอยู่ใน DataFrame
เพื่อความสะดวก pandas ถูก import ไว้เป็น pd และไฟล์ 'tweets.csv' ถูกโหลดเข้า DataFrame ชื่อ tweets_df แล้ว พร้อมทั้งมีโค้ดบางส่วนจากงานก่อนหน้าให้ด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้น: การเขียนฟังก์ชัน
คำแนะนำการฝึกหัด
- เพิ่มบล็อก
tryเพื่อให้เมื่อฟังก์ชันถูกเรียกใช้ด้วยอาร์กิวเมนต์ที่ถูกต้อง ฟังก์ชันจะประมวลผล DataFrame และคืนค่าเป็น dictionary ของผลลัพธ์ - เพิ่มบล็อก
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)