รวบรวมทุกอย่างเข้าด้วยกัน (3)
ในแบบฝึกหัดที่แล้ว คุณได้พัฒนาฟังก์ชัน count_entries() ต่อยอดโดยเพิ่มบล็อก try-except เข้าไป เพื่อให้ผู้ใช้ได้รับข้อความที่เป็นประโยชน์เมื่อระบุชื่อคอลัมน์ที่ไม่มีอยู่ใน DataFrame ในแบบฝึกหัดนี้ คุณจะเปลี่ยนมาใช้การ raise ValueError แทน เมื่อผู้ใช้ระบุชื่อคอลัมน์ที่ไม่มีใน DataFrame
เพื่อความสะดวก pandas ถูก import ไว้เป็น pd และไฟล์ 'tweets.csv' ถูกโหลดเข้า DataFrame ชื่อ tweets_df แล้ว โค้ดบางส่วนจากงานก่อนหน้าก็ถูกเตรียมไว้ให้แล้วเช่นกัน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้น: การเขียนฟังก์ชัน
คำแนะนำการฝึกหัด
- ถ้า
col_nameไม่ใช่ คอลัมน์ที่มีอยู่ใน DataFramedfให้ raiseValueError 'The DataFrame does not have a ' + col_name + ' column.' - เรียกใช้ฟังก์ชัน
count_entries()ที่สร้างขึ้นใหม่เพื่อวิเคราะห์คอลัมน์'lang'ของtweets_dfแล้วเก็บผลลัพธ์ไว้ในตัวแปรresult1 - แสดงผล
result1ซึ่งเขียนโค้ดไว้ให้แล้ว กด ส่งคำตอบ เพื่อดูผลลัพธ์ ในแบบฝึกหัดถัดไป คุณจะได้เห็นว่าโค้ดนี้ raiseValueErrorได้อย่างถูกต้อง
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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)