시작하기무료로 시작하기

청크 단위로 데이터를 불러오는 이터레이터 작성 (4)

이전 연습 문제에서는 첫 번째 DataFrame 청크의 데이터만 처리했어요. 이번에는 데이터셋의 모든 DataFrame 청크에 대해 결과를 집계합니다. 즉, 이제는 데이터셋의 전체를 처리하게 됩니다. 큰 데이터를 작은 조각으로 나눠서 처리하면서도 전체를 다룰 수 있다는 점이 아주 유용해요!

현재 디렉터리에 있는 'ind_pop_data.csv' 데이터를 사용할 거예요. 패키지 pandasmatplotlib.pyplot은 각각 pd, plt로 이미 임포트되어 있습니다.

이 연습은 강의의 일부입니다

Python 도구 상자

강의 보기

연습 안내

  • pd.DataFrame()을 사용해 빈 DataFrame data를 초기화하세요.
  • for 루프에서 urb_pop_reader를 반복(iterate)해 데이터셋의 모든 DataFrame 청크를 처리하세요.
  • pd.concat()에 DataFrame의 리스트를 전달해 datadf_pop_ceb를 연결하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Initialize reader object: urb_pop_reader
urb_pop_reader = pd.read_csv('ind_pop_data.csv', chunksize=1000)

# Initialize empty DataFrame: data
data = ____

# Iterate over each DataFrame chunk
for df_urb_pop in ____:

    # Check out specific country: df_pop_ceb
    df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == 'CEB']

    # 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 = ____

# Plot urban population data
data.plot(kind='scatter', x='Year', y='Total Urban Population')
plt.show()
코드 편집 및 실행