分块处理数据(1)
有时数据源体量很大,把整个数据集都放入内存会非常耗费资源。本练习中,您将逐行处理文件的前 1000 行,统计数据集中某一列里各个国家出现的次数,并将其保存到一个字典中。
当前目录下已提供 csv 文件 'world_dev_ind.csv'。首先,您需要使用所谓的上下文管理器来打开该文件。例如,命令 with open('datacamp.csv') as datacamp 会在上下文管理器中将 csv 文件 'datacamp.csv' 绑定为 datacamp。这里,with 语句就是上下文管理器,它的作用是在打开文件连接时高效管理资源。
如果您想进一步了解上下文管理器,请参阅 DataCamp 的 Python 数据导入课程。
本练习是课程的一部分
Python 工具箱
练习说明
- 使用
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)