开始使用免费开始使用

编写迭代器按块加载数据(2)

在上一个练习中,您使用 read_csv() 从大型数据集中按块读取 DataFrame。在本练习中,您将使用更大的 DataFrame 分块大小读取文件,然后处理第一块数据。

在处理数据时,您将创建一个新的 DataFrame,只包含来自特定国家的行。随后,您会将新 DataFrame 中的两个列 'Total Population''Urban population (% of total)' 进行 zip。最后,您会从该 zip 对象创建一个由元组组成的列表,其中每个元组由上述两个列各取一个值构成。

您将使用当前目录中的 'ind_pop_data.csv' 数据。pandas 已以 pd 导入。

本练习是课程的一部分

Python 工具箱

查看课程

练习说明

  • 使用 pd.read_csv() 以大小为 1000 的分块读取 'ind_pop_data.csv' 文件。将结果赋给 urb_pop_reader
  • 从可迭代对象 urb_pop_reader 中获取第一个 DataFrame 分块,并将其赋给 df_urb_pop
  • 仅选择 df_urb_pop'CountryCode''CEB' 的行。为此,请在 df_urb_pop[____] 的方括号内比较 df_urb_pop['CountryCode'] 是否与 'CEB' 相等
  • 使用 zip()df_pop_ceb'Total Population''Urban population (% of total)' 两列打包在一起。将得到的 zip 对象赋给 pops

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Initialize reader object: urb_pop_reader
urb_pop_reader = pd.read_csv(____, ____)

# Get the first DataFrame chunk: df_urb_pop
df_urb_pop = next(____)

# Check out the head of the DataFrame
print(df_urb_pop.head())

# Check out specific country: df_pop_ceb
df_pop_ceb = df_urb_pop[____]

# Zip DataFrame columns of interest: pops
pops = zip(____, ____)

# Turn zip object into list: pops_list
pops_list = list(pops)

# Print pops_list
print(pops_list)
编辑并运行代码