撰寫疊代器以分批載入資料(3)
你現在應該已經熟悉如何分批讀取並處理資料了。讓我們再進一步,加上一個新的欄位到 DataFrame。
從上一個練習的程式碼出發,你會使用「串列生成式」來從先前產生的 tuple 串列建立新欄位 'Total Urban Population' 的值。回想上一個練習,每個 tuple 的第一與第二個元素分別來自欄位 'Total Population' 與 'Urban population (% of total)'。因此,新的欄位 'Total Urban Population' 的值就是這兩個元素的乘積。此外,因為第二個元素是百分比,你需要將整個結果除以 100,或等價地乘上 0.01。
你也會將這個新欄位的資料繪圖,視覺化都市人口相關資料。
pandas 與 matplotlib.pyplot 已分別以 pd 與 plt 匯入,供你使用。
本練習屬於課程
Python 工具箱
練習說明
- 撰寫一個串列生成式,從
pops_list產生新欄位'Total Urban Population'的值清單。輸出運算式 應為pops_list中每個 tuple 的第一與第二個元素的乘積。由於第二個元素是百分比,你需要將結果乘以0.01或除以100。另外,注意欄位'Total Urban Population'應只包含整數值。為了確保這點,請用int()將輸出運算式轉為整數。 - 建立一張「散佈圖」,x 軸使用
'Year'欄位的值,y 軸使用'Total Urban Population'欄位的值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Code from previous exercise
urb_pop_reader = pd.read_csv('ind_pop_data.csv', chunksize=1000)
df_urb_pop = next(urb_pop_reader)
df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == 'CEB']
pops = zip(df_pop_ceb['Total Population'],
df_pop_ceb['Urban population (% of total)'])
pops_list = list(pops)
# Use list comprehension to create new DataFrame column 'Total Urban Population'
df_pop_ceb['Total Urban Population'] = [____]
# Plot urban population data
df_pop_ceb.plot(kind=____, x=____, y=____)
plt.show()