Google Spreadsheetからデータを取得してPandasのDataframeに変換する例

最近はPythonを書く機会が多いのでPythonネタをメモ程度に書き留めておきます。

事前準備

データの準備

動作確認用のスプレッドシートを作成し、サービスアカウントで編集できるように権限を設定します。

(GoogleAPIを使用するためにサービスアカウントを使用しますが、設定手順は割愛します)

そのスプレッドシートに「iris」という名前のシートを作成し、シートの内容を以下のようにします。

f:id:ariarijp:20170528204805p:plain

Irisのデータは以下のリンクなどから入手できます。

UCI Machine Learning Repository: Iris Data Set

環境の準備

venv などを使用して、以下の requirements.txt を使用できるようにしてください。

google-api-python-client==1.6.2
httplib2==0.10.3
numpy==1.12.1
oauth2client==4.1.0
pandas==0.20.1
pyasn1==0.2.3
pyasn1-modules==0.0.8
python-dateutil==2.6.0
pytz==2017.2
rsa==3.4.2
six==1.10.0
uritemplate==3.0.0

コード例

処理についてはコメントを参照してください。

import httplib2
import os

import sys
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials

import pandas as pd

CLIENT_SECRET_FILE = os.environ.get('CLIENT_SECRET_FILE', 'client_secret.json')
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
DISCOVERY_URL = 'https://sheets.googleapis.com/$discovery/rest?version=v4'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    filename=CLIENT_SECRET_FILE,
    scopes=SCOPES)
http = credentials.authorize(httplib2.Http())
service = discovery.build(serviceName='sheets',
                          version='v4',
                          http=http,
                          discoveryServiceUrl=DISCOVERY_URL)

# スプレッドシートのIDをコマンドライン引数から取得する
spreadsheet_id = sys.argv[1]

# スプレッドシートからデータを取得する
values = service.spreadsheets().values() \
    .get(spreadsheetId=spreadsheet_id,
         range='iris!A:E') \
    .execute() \
    .get('values', [])

# 取得したデータをDataframeにする
df = pd.DataFrame \
    .from_records(data=values[1:],
                  columns=values[0])

# 全ての列がobject型になってしまうので、数値の列の型をfloatに変換する
df = df.astype({
    'sepal_length': float,
    'sepal_width': float,
    'petal_length': float,
    'petal_width': float,
})

# 動作確認
print('[df.describe]')
print(df.describe())
print()
print('[df.head]')
print(df.head(5))

実行

$ python example.py スプレッドシートID
[df.describe]
       sepal_length  sepal_width  petal_length  petal_width
count    150.000000   150.000000    150.000000   150.000000
mean       5.843333     3.054000      3.758667     1.198667
std        0.828066     0.433594      1.764420     0.763161
min        4.300000     2.000000      1.000000     0.100000
25%        5.100000     2.800000      1.600000     0.300000
50%        5.800000     3.000000      4.350000     1.300000
75%        6.400000     3.300000      5.100000     1.800000
max        7.900000     4.400000      6.900000     2.500000

[df.head]
   sepal_length  sepal_width  petal_length  petal_width      species
0           5.1          3.5           1.4          0.2  Iris-setosa
1           4.9          3.0           1.4          0.2  Iris-setosa
2           4.7          3.2           1.3          0.2  Iris-setosa
3           4.6          3.1           1.5          0.2  Iris-setosa
4           5.0          3.6           1.4          0.2  Iris-setosa

まとめ

とにかくなんでもPandasのデータフレームに持ち込めれば、Pandasの強力な機能の数々を使うことができるので、 様々なデータソースを使った処理を書いたり、分析したりする人にとって、Pandasはうれしいツールですね。もうちょっと勉強しつつ、実践投入していく予定です。

Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理

Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理

この本は図書館で借りたことがあったけど、手元に置いておきたいかも。