LoginSignup
3
1

More than 5 years have passed since last update.

google スプレッドシート => BigQuery => pandas

Last updated at Posted at 2019-02-08

「google スプレッドシート」をソースに指定した BigQuery のテーブルを「read_gbq」する方法を説明します。

権限の設定

スプレッドシートへの参照権限追加

使用するサービスアカウントに対象のスプレッドシートへの参照権限を付与します。
なお、ここではサービスアカウントを使用することを前提としています。

APIの有効化

GCP コンソールから、「APIとサービス」を選択して、「Google Drive API」「Google Sheets API」 を有効にする。

サービスアカウントにスコープを設定する

GCP コンソールから、「セキュリティ」を選択して、つぎの2つをカンマ区切りで設定する。

上2つの情報はつぎのURLから得たものであり、助かりました。
https://blog.nijohando.jp/post/building-private-timestamp-system-1/

pandas と pandas-gbq のバージョンを確認する

read_gbq の credentials というパラメータを使うのですが、これが次のバージョン以降から追加されています。
New in version 0.8.0 of pandas-gbq.
New in version 0.24.0.<= pandas

これ以前のバージョンの場合は、更新します。

pip install --upgrade pandas-gbq
pip install --upgrade pandas

コードを書く

注意点はつぎの3つの Scope を追加する必要があることです。

この、Scope を追加するために credentials があるバージョンが必要でした。

import pandas as pd
from google.oauth2.service_account import Credentials

query = """
SELECT * FROM `dogs-111.pretty.beagle`
"""

cred = Credentials.from_service_account_file("./auth/account.json")
cred = cred.with_scopes(
    ["https://www.googleapis.com/auth/drive.readonly", 
     "https://www.googleapis.com/auth/spreadsheets.readonly",
     "https://www.googleapis.com/auth/cloud-platform"])
df_result = pd.read_gbq(query, project_id="dogs-111", dialect="standard", credentials=cred)

最後に

今回紹介した方法とは別の方法もあるかもしれません。私がかなり苦戦したので、知識の共有として一事例を紹介しました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1