여러 워크시트에서 데이터 가져오기

pandas로 빠르고 간편한 데이터 적재

Amany Mahfouz

Instructor

로딩할 시트 선택

  • read_excel()은 기본적으로 첫 번째 시트를 로드합니다
  • 다른 시트를 로드하려면 sheet_name 키워드를 사용합니다
  • 시트는 이름 또는 (0부터 시작하는) 위치 번호로 지정합니다
  • 여러 시트를 한꺼번에 로드하려면 이름/번호 리스트를 전달합니다
  • read_excel()에 전달한 인수는 읽는 모든 시트에 적용됩니다
pandas로 빠르고 간편한 데이터 적재

로딩할 시트 선택

스프레드시트 프로그램 스크린샷. 두 시트 탭이 보임

pandas로 빠르고 간편한 데이터 적재

선택 시트 로딩

# 위치 인덱스로 두 번째 시트 가져오기
survey_data_sheet2 = pd.read_excel('fcc_survey.xlsx',
                                   sheet_name=1)

# 이름으로 두 번째 시트 가져오기 survey_data_2017 = pd.read_excel('fcc_survey.xlsx', sheet_name='2017')
print(survey_data_sheet2.equals(survey_data_2017))
True
pandas로 빠르고 간편한 데이터 적재

모든 시트 로딩

  • sheet_name=None을 read_excel()에 전달하면 통합 문서의 모든 시트를 읽습니다
survey_responses = pd.read_excel("fcc_survey.xlsx", sheet_name=None)

print(type(survey_responses))
<class 'collections.OrderedDict'>
for key, value in survey_responses.items():
    print(key, type(value))
2016 <class 'pandas.core.frame.DataFrame'>
2017 <class 'pandas.core.frame.DataFrame'>
pandas로 빠르고 간편한 데이터 적재

종합하기

# 로드한 모든 시트를 담을 빈 데이터프레임 생성
all_responses = pd.DataFrame()

# 딕셔너리의 데이터프레임을 순회 for sheet_name, frame in survey_responses.items(): # 데이터의 연도를 알 수 있도록 열 추가 frame["Year"] = sheet_name
# 데이터프레임을 all_responses에 추가 all_responses = pd.concat([all_responses, frame])
# 데이터의 연도 확인 print(all_responses.Year.unique())
['2016' '2017']
pandas로 빠르고 간편한 데이터 적재

연습해 봅시다!

pandas로 빠르고 간편한 데이터 적재

Preparing Video For Download...