본문 바로가기
배움 로그/data science

Python/Pandas - Google Drive/Sheet에서 데이터 프레임으로 데이터 불러오기, 저장하기

by eple 2023. 3. 21.
728x90
반응형

 

 


얼마 전 데이터 크롤링 이후
Python에서 CSV 파일로 결과를 저장했는데,  
내 노트북에 Office류가 
인증이 되어있지 않은 것을 확인했다 ㅎㅎ

노트북에서 Office 잘 안 쓰는데
결과를 보자고 돈을 지불하자니
애매하여 구글 드라이브의 구글시트를
활용하기로...

오랜만에 또 연동하려니
생각이 잘 안 나서 이번에는 기록으로 남겨둔다! 

 

    사전 준비

  • Google Cloud 내 프로젝트 계정이 있을 경우ㅎ 
  • python ↔ Google Drive/Sheet 연동을 위한 신청인증키 발급 단계 

  • 인증키 생성 및 다운로드 
    • IAM & Admin에서 service account 생성
    • 생성한 account의 Key(json파일)를 다운로드하여 내 프로젝트(workspace)에 위치 

 

  • 구글 시트 생성 후 공유자에 service account 추가 
    • 우측에 공유 버튼 클릭 
    • 서비스 account의 email 주소 추가 

 

    Python  필요 라이브러리 설치 

  • 필요 라이브러리는 3가지, gspread, 인증라이브러리, 그리고 구글시트의 데이터프레임인식 라이브러리 
pip install gspread
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
pip install gspread-dataframe

 

    Worksheet - Data.Frame으로 읽어오기

  • Data.Frame로 읽어오기 위해서 첫째로 인증 및 데이터가 있는 URL 주소 입력
  • 구글 시트의 데이터를 데이터 프레임으로 읽어오기 위한 함수로는 get_as_dataframe
# Google Drive - googlesheet 인증 
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
]

json_file_name = '발급받은 인증키가 담긴 json 파일 명'
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
gc = gspread.authorize(credentials)
spreadsheet_url = '작성하려는 구글 시트의 URL'

# 스프레스시트 문서 가져오기 
doc = gc.open_by_url(spreadsheet_url)

# 기준정보 load 
worksheet = doc.worksheet('생성할 워크시트 명')
stockcode = get_as_dataframe(worksheet=worksheet)

 

    Data.Frame을 Worksheet으로 내보내기

  • 데이터 프레임을 워크시트로 내보내기 위한  위한 함수로는 set_as_dataframe 함수를 활용하면 된다.
  • 때로 숫자코드가 앞에 00이 붙거나 한 경우, 문자로 인식시킬 필요가 있는데,
    그럴 경우, string_escaping 옵션을 'full'로 지정해 주면 된다!   
# 시트 선택하기
worksheet1 = doc.worksheet('시트1')

# write to dataframe
worksheet1.clear()
set_with_dataframe(worksheet=worksheet1, dataframe=final_all_result, 
					include_index=False, include_column_header=True, 
                    resize=True, string_escaping='full')

 

* 참조 글

 

Welcome to gspread-dataframe’s documentation! — gspread-dataframe documentation

Parameters: worksheet – the gspread worksheet to set with content of DataFrame. dataframe – the DataFrame. row – Row at which to start writing the DataFrame. Default is 1. col – Column at which to start writing the DataFrame. Default is 1. include_

gspread-dataframe.readthedocs.io

 

댓글