データをチャンク単位で処理する(1)
データソースのサイズが非常に大きい場合、データセット全体をメモリに読み込むとリソースの消費が大きくなりすぎることがあります。この演習では、ファイルの最初の 1000 行を 1 行ずつ処理し、データセットの特定の列に各国名が何回登場するかを集計した辞書を作成します。
CSV ファイル 'world_dev_ind.csv' は現在のディレクトリに用意されています。まず、コンテキストマネージャーを使ってこのファイルへの接続を開く必要があります。たとえば、with open('datacamp.csv') as datacamp というコマンドは、CSV ファイル 'datacamp.csv' をコンテキストマネージャー内で datacamp として紐付けます。ここで with 文がコンテキストマネージャーであり、ファイルへの接続を開く際にリソースを効率よく管理することを目的としています。
コンテキストマネージャーについてさらに詳しく学びたい場合は、DataCamp の「Importing Data in Python」コースを参照してください。
この演習はコースの一部です
Python Toolbox
演習の手順
open()を使って、CSV ファイル'world_dev_ind.csv'をコンテキストマネージャーでfileとして紐付けます。forループを完成させ、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)