Data in stukken verwerken (1)
Soms zijn databronnen zo groot dat het te veel geheugen kost om de hele gegevensset in het geheugen op te slaan. In deze oefening verwerk je de eerste 1000 rijen van een bestand regel voor regel om een woordenboek te maken met telwaarden van hoe vaak elk land voorkomt in een kolom van de gegevensset.
Het csv-bestand 'worlddevind.csv' staat in je huidige map. Om te beginnen moet je een verbinding met dit bestand openen met wat een contextmanager wordt genoemd. Bijvoorbeeld: de opdracht with open('datacamp.csv') as datacamp koppelt het csv-bestand 'datacamp.csv' als datacamp binnen de contextmanager. Hier is de with-instructie de contextmanager, en het doel is om ervoor te zorgen dat resources efficiënt worden toegewezen wanneer je een verbinding met een bestand opent.
Wil je meer leren over contextmanagers? Bekijk dan de DataCamp-cursus over Importing Data in Python.
Deze oefening maakt deel uit van de cursus
Python-gereedschapskist
Oefeninstructies
- Gebruik
open()om het csv-bestand 'worlddevind.csv' alsfilete koppelen in de contextmanager. - Maak de
for-loop af zodat deze 1000 keer itereert om de loopbody uit te voeren en alleen de eerste 1000 rijen van het bestand te verwerken.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# 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)