VSCodeのDocker開発コンテナでJupyter Notebookを開いてAthenaのクエリを実行し可視化する

pythondockervscodeawsetl

ローカルでJupyter Notebookを動かすために以前はjupyter/datascience-notebookのイメージを立ち上げていた。 Notebookはエディタとしての機能に乏しいため通常のコードを書くのが大変だったのだが、 VSCodeのPython extensionにはJupyter notebookサポートが入っていてそのまま開けて実行できるのを知ったので移行することにした。 今回はVSCodeのDocker開発コンテナからNotebookを開いてAthenaのクエリを実行し可視化する。

VSCodeのRemote DevelopmentでSageMakerのコンテナ環境でモデルを開発する - sambaiz-net

環境構築

~/.awsをマウントする。Dockerfileは上記の記事のと同じ。

{
	"name": "Python",
	"build": {
		"dockerfile": "Dockerfile"
	},
	"settings": {
		"terminal.integrated.shell.linux": "/bin/bash",
		"python.pythonPath": "/usr/local/bin/python",
		"python.linting.enabled": true,
		"python.linting.pylintEnabled": false,
		"python.linting.flake8Enabled": true,
		"python.linting.flake8Path": "/usr/local/bin/flake8",
		"editor.formatOnSave": true,
		"python.formatting.provider": "yapf",
		"python.formatting.yapfPath": "/usr/local/bin/yapf",
		"python.linting.mypyEnabled": true,
		"python.linting.mypyPath": "/usr/local/bin/mypy",
	},
	"extensions": [
		"ms-python.python"
	],
	"mounts": [
		"source=${localEnv:HOME}/.aws,target=/root/.aws,type=bind,readonly"
	]
}

アプリケーションで使うパッケージはPoetryでインストールすることにしている。

PoetryでPythonの依存パッケージを管理する - sambaiz-net

KernalをvenvのPythonに切り替えるためにipykernelをインストールする必要がある。

[tool.poetry.dependencies]
python = "^3.8"
PyAthena = "^1.11.1"
pandas = "^1.1.1"
ipykernel = "^5.3.4"
matplotlib = "^3.3.1"

クエリの実行

Notebookを開いてKernelをvenvのPythonに切り替える。AthenaのクライアントにはPyAthenaを使う。 この例ではクエリを実行し、横軸にlagを、縦軸に自己相関係数を取ったコレログラムを描画している。

from pyathena import connect
import pandas as pd
import matplotlib.pyplot as plt

conn = connect(s3_staging_dir='s3://*****', region_name='ap-northeast-1')
df = pd.read_sql(query, conn)
print(df)

x = list(range(25))
y = [df['value'].autocorr(lag=i) for i in x]
plt.bar(x, y, label="autocorrelation")
plt.xticks(x)
plt.show()