Python 라이브러리 중 데이터분석쪽에서 가장 유명한 pandas에서 제공하는 to_gbq를 사용하면 GCP(Google Cloud Platform)의 Bigquery와 통신이 가능하다.
DB를 Dataframe형태로 불러올 수도 있고,반대로 dataframe을 Bigquery로 업로드 할수도 있다.
제공하는 to_gbq는 크게 append / replace / fail이 있으며 이를 활용하여,
사용자가 실수로 잘못된 데이터를 입력하였을때 기존 데이터와 비교하여 특정 부분만 업데이트하는 방식을 사용할 것이다.
엑셀 -> Bigquery(업로드) append / replace
from datetime import datetime from google.cloud import storage import os import io from PIL import Image from google.oauth2 import service_account import pandas_gbq import os import pandas as pd os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="Google Credentials.json파일 경로/파일명.json" #데이터 호출 dataframe=pd.read_excel('Bigquery에 적재하고 싶은 엑셀파일.xlsx') #-------------------------------------------csv명 # Credentials JSON파일은 [IAM 및 관리자] -> [서비스 계정] 에서 발급 가능하다. cd = service_account.Credentials.from_service_account_file("Google Credentials.json파일 경로/파일명.json",) #프로젝트의 ID /프로젝트명이 아니다 주의할것 project_id = '프로젝트-ID' #destination_table = '데이터세트명.데이터 테이블명' destination_table = '데이터세트명.데이터 테이블명' #append모드 / replace모드 / fail<-오류 반환 모드 dataframe.to_gbq(destination_table,project_id, if_exists='append', credentials=cd) print('migration complete') |
Bigquery -> Dataframe (쿼리문으로 가져온다)
import os from google.cloud import bigquery os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="Google Credentials.json파일 경로/파일명.json" client = bigquery.Client() sql = """ SELECT `테이블명`.`컬럼명` AS `원하는명칭`, FROM `프로젝트명 """ df = client.query(sql).to_dataframe() |
728x90
반응형
'프로그래밍 > Python' 카테고리의 다른 글
[jupyter notebook]kernel starting please wait, connection failed 에러 해결하기 (0) | 2022.10.04 |
---|---|
[Python(파이썬)]각기 다른 Dataframe에서 동일 값이면 replace(변경)하기 (0) | 2022.09.14 |
pyinstaller 용량 줄이기(순정 Python) (0) | 2022.08.17 |
[GCP]Bigquery로 Dataframe전달할때 GenericGBQException 에러해결하기 (0) | 2022.08.10 |
[GCP]Bigquery로 데이터 전송하기(Dataframe / Python / pandas_gbq) (0) | 2022.08.10 |