開始使用免費開始

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

最後一哩路。你已經學會如何把大型資料集分批處理。在這個最終練習中,你會把處理資料的程式碼整合到一個函式裡,之後就能重複使用,不必每次都重寫。

你將定義函式 plot_pop(),它有兩個引數:要處理的檔案名稱,以及你想在資料集中處理的國家代碼。

因為你先前練習中寫的所有程式碼都會收進 plot_pop(),呼叫這個函式就會自動完成以下工作:

  • 逐批載入檔案、
  • 建立新的「都會人口」欄位、以及
  • 繪製都會人口資料。

這步驟不少,但有了這個函式,你就能方便地針對任何檔案與國家代碼重複進行處理與視覺化!

你將使用目前目錄中的 'ind_pop_data.csv' 資料。套件 pandas 與 matplotlib.pyplot 已分別以 pdplt 匯入供你使用。

完成後,花點時間看看圖表,回顧你剛學到的新技能。學習還沒結束!如果你喜歡這份資料,也可以到 Kaggle 繼續探索那個已預先處理過的版本。

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • 定義函式 plot_pop(),它有兩個引數:第一個是要處理檔案的 filename,第二個是資料集中要處理的國家代碼 country_code
  • 呼叫 plot_pop(),處理檔案 'ind_pop_data.csv' 中國家代碼為 'CEB' 的資料。
  • 再呼叫 plot_pop(),處理檔案 'ind_pop_data.csv' 中國家代碼為 'ARB' 的資料。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define plot_pop()
def ____(____, ____):

    # Initialize reader object: urb_pop_reader
    urb_pop_reader = pd.read_csv(filename, chunksize=1000)

    # Initialize empty DataFrame: data
    data = pd.DataFrame()
    
    # Iterate over each DataFrame chunk
    for df_urb_pop in urb_pop_reader:
        # Check out specific country: df_pop_ceb
        df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == country_code]

        # Zip DataFrame columns of interest: pops
        pops = zip(df_pop_ceb['Total Population'],
                    df_pop_ceb['Urban population (% of total)'])

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

        # Use list comprehension to create new DataFrame column 'Total Urban Population'
        df_pop_ceb['Total Urban Population'] = [int(tup[0] * tup[1] * 0.01) for tup in pops_list]
        
        # Concatenate DataFrame chunk to the end of data: data
        data = pd.concat([data, df_pop_ceb])

    # Plot urban population data
    data.plot(kind='scatter', x='Year', y='Total Urban Population')
    plt.show()

# Set the filename: fn
fn = 'ind_pop_data.csv'

# Call plot_pop for country code 'CEB'


# Call plot_pop for country code 'ARB'
編輯並執行程式碼