เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

นำทุกอย่างมารวมกัน (2)

เยี่ยมมาก! คุณได้ขยายการวิเคราะห์ภาษาบน Twitter จากบทที่แล้วโดยเพิ่ม default argument สำหรับชื่อคอลัมน์เข้าไปแล้ว ตอนนี้เราจะพัฒนาฟังก์ชันนี้ต่ออีกขั้น ด้วยการให้ผู้ใช้ส่งชื่อคอลัมน์ได้หลายชื่อตามต้องการผ่าน flexible argument!

เพื่อความสะดวก pandas ได้ถูก import ไว้เป็น pd และไฟล์ 'tweets.csv' ได้ถูกโหลดเข้า DataFrame tweets_df เรียบร้อยแล้ว พร้อมกับโค้ดบางส่วนจากงานก่อนหน้าของคุณ

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Python เบื้องต้น: การเขียนฟังก์ชัน

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เติมส่วนหัวของฟังก์ชันให้ครบโดยระบุพารามิเตอร์สำหรับ DataFrame df และ flexible argument *args
  • เติมลูป for ภายในฟังก์ชันให้ครบ โดยให้ลูปวนซ้ำผ่าน tuple args
  • เรียกใช้ count_entries() โดยส่ง DataFrame tweets_df และชื่อคอลัมน์ 'lang' แล้วกำหนดผลลัพธ์ให้กับตัวแปร result1
  • เรียกใช้ count_entries() โดยส่ง DataFrame tweets_df และชื่อคอลัมน์ 'lang' กับ 'source' แล้วกำหนดผลลัพธ์ให้กับตัวแปร 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)
แก้ไขและรันโค้ด