การประมวลผลข้อมูลเป็นชุด (1)
บางครั้งแหล่งข้อมูลอาจมีขนาดใหญ่มากจนการโหลดชุดข้อมูลทั้งหมดไว้ในหน่วยความจำพร้อมกันนั้นใช้ทรัพยากรมากเกินไป ในแบบฝึกหัดนี้ คุณจะประมวลผล 1000 แถวแรกของไฟล์ทีละบรรทัด เพื่อสร้าง dictionary ที่นับจำนวนครั้งที่แต่ละประเทศปรากฏในคอลัมน์หนึ่งของชุดข้อมูล
ไฟล์ csv ชื่อ 'world_dev_ind.csv' อยู่ในไดเรกทอรีปัจจุบันพร้อมให้ใช้งาน ขั้นแรกต้องเปิดการเชื่อมต่อกับไฟล์นี้โดยใช้สิ่งที่เรียกว่า context manager ตัวอย่างเช่น คำสั่ง with open('datacamp.csv') as datacamp จะผูกไฟล์ csv 'datacamp.csv' เข้ากับตัวแปร datacamp ใน context manager โดย with statement ทำหน้าที่เป็น context manager เพื่อให้แน่ใจว่าทรัพยากรถูกจัดการอย่างมีประสิทธิภาพเมื่อเปิดการเชื่อมต่อกับไฟล์
หากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับ context manager ดูได้ที่ คอร์ส DataCamp เรื่อง Importing Data in Python
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python Toolbox
คำแนะนำการฝึกหัด
- ใช้
open()เพื่อผูกไฟล์ csv'world_dev_ind.csv'เป็นfileใน context manager - เติมโค้ดใน
forloop ให้วนซ้ำ 1000 รอบ เพื่อประมวลผลเฉพาะ 1000 แถวแรกของไฟล์
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Open a connection to the file
with ____ as ____:
# Skip the column names
file.readline()
# Initialize an empty dictionary: counts_dict
counts_dict = {}
# Process only the first 1000 rows
for j in ____:
# Split the current line into a list: line
line = file.readline().split(',')
# Get the value for the first column: first_col
first_col = line[0]
# If the column value is in the dict, increment its value
if first_col in counts_dict.keys():
counts_dict[first_col] += 1
# Else, add to the dict and set value to 1
else:
counts_dict[first_col] = 1
# Print the resulting dictionary
print(counts_dict)