開始使用免費開始

撰寫迭代器以分批載入資料(2)

在前一個練習中,你使用 read_csv() 從大型資料集讀入多個 DataFrame 區塊。這一題你會用更大的區塊大小讀入檔案,然後處理第一個區塊的資料。

處理資料時,你會建立另一個 DataFrame,只包含特定國家的列。接著把新 DataFrame 中的兩個欄位('Total Population''Urban population (% of total)')用 zip 合併。最後,你會從該 zip 物件建立一個 tuple 清單,其中每個 tuple 都由上述兩個欄位各取一個值組成。

你將使用位在目前目錄中的 'ind_pop_data.csv'pandas 已以 pd 匯入。

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • 使用 pd.read_csv() 讀入 'ind_pop_data.csv',並設定每個區塊大小為 1000。將結果指定為 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)
編輯並執行程式碼