分批處理資料(1)
有時候資料來源的檔案很大,把整個資料集一次放進記憶體會非常耗資源。在本練習中,你會逐行處理檔案的前 1000 列,建立一個字典,統計資料集中某一欄位中各國家出現的次數。
目前資料夾中已提供 csv 檔 'worlddevind.csv' 可供你使用。開始之前,你需要用所謂的情境管理器(context manager)來開啟這個檔案。例如,with open('datacamp.csv') as datacamp 這行指令會在情境管理器中把 csv 檔 'datacamp.csv' 綁定為 datacamp。這裡的 with 陳述式就是情境管理器,用意是確保在開啟檔案連線時,能有效率地配置與釋放資源。
如果你想更深入了解情境管理器,請參考 DataCamp 的課程「Importing Data in Python」。(https://www.datacamp.com/courses/importing-data-in-python-part-1)
本練習屬於課程
Python 工具箱
練習說明
- 使用
open(),在情境管理器中將 csv 檔 'worlddevind.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)