0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Snowflake workspace ノートブックデモ をちゃんと読み解いてから実行してみた

0
Last updated at Posted at 2026-07-05

Snowflakeのトライアル環境を作りました。

ワークスペースを開いたら

チュートリアルを始めましょう
ノートブックデモ
上位10人の顧客を検索

というリンクがあるじゃないですか。
image.png

リンクをクリックすると「demo_notebook.ipynb」が開きました。
すぐ実行しても「ふーん」で終わってしまうので、読み解いてみます。

読み解く

※今回、ノートブックに表示されたMarkdownをそのまま貼り付けているため、
 このQiitaページの目次的なところにもMarkdownの「#」が反映されちゃってます。

セル1(Markdown)

Welcome to Snowflake Notebooks in Workspaces! 🌟

Snowflake Notebooks are fully-managed Jupyter-powered notebook built for end-to-end DS and ML development on Snowflake data.

This includes:

  • 🐍 Familiar Jupyter experience - Directly connected to the governed Snowflake data.
  • 💻 Inside Snowflake Workspaces - Organize and run notebooks alongside your other files.
  • 🧠 Powerful for AI/ML - Runs in our pre-built Container Runtime (CPU or GPU) with popular DS/ML packages pre-installed.
  • 🏛️ Governed collaboration - Enable multiple users to collaborate via Git-backed Workspaces or Shared Workspaces.

Snowflake Notebooks が Jupyter ベースであること、Container Runtime(CPU/GPU)で動くこと、Git 連携やコラボレーションが可能なことが説明されています。

セル2(Markdown)

1. Connect and run the notebook

Press [Run all] or [Connect] to create and connect your notebook to a service.

Optionally, run the below Python cell to inspect all pre-installed packages. To use a package, run import <package_name>. See example in "4. Visualize customer patterns". Learn more about Managing packages and runtime

[Run all] または [Connect] を押して、ノートブックをサービスに作成・接続します。

ということでそのままなんですが、補足をすると
Snowflake ノートブックは、裏側でContainer Runtime(コンテナサービス)が動いています。
ノートブック単体ではコードを実行できず、まずコンテナに接続する必要があります。

  1. [Run all] か [Connect] をクリック → サービス(コンテナ)が起動し、ノートブックと繋がる
  2. 接続完了後 → Pythonセルや SQLセルが実行可能になる

こんな感じ。

セル3(Python)

!pip freeze # Shows all pre-installed packages

pip freeze でランタイムにプリインストールされているパッケージ一覧を表示します。

セル4(Markdown)

2. Create some customer data

This query generates a random table of customer data to explore

この下にあるセル5のクエリ説明です。

セル5(SQL)

select
  seq4() as customer_id,
  'customer_' || (customer_id + 1) as name,
  'customer_' || (customer_id + 1) || '@example.com' as email,
  dateadd(day, -uniform(0, 3650, random()), current_date()) as signup_date,
  round(uniform(100, 100000, random()) / 100, 2) as lifetime_value
from table(generator(rowcount => 1000));

generator() を使って 1,000 件のダミー顧客データ(ID、名前、メール、登録日、LTV)を生成します。

セル6(Markdown)

3. Find high value customers

This will show customers worth $800 or more. As you'll see, we're referencing the dataframe created above.

これも先ほどと同様、この下にあるセル7のクエリ説明です。

セル7(SQL)

SELECT * FROM {{dataframe_1}} WHERE "LIFETIME_VALUE" > 800;

LTVが$800超データを取ってくるクエリです。

{{dataframe_1}}

これ、jinjaテンプレートですね。
dbtじゃなくても使えるの知らなかった。
CoCo in Snowsightで聞いてみたら、ノートブックではjinjaテンプレートは変数としてのみ使えるみたいです。

セル8(Markdown)

4. Visualize customer patterns

View the chart to see the distribution of customer tenure vs spend. Again, we're using the dataframe that was generated above.
この下にあるセル9のPythonコードの説明ですね。

チャートを見て、顧客のtenureと支出額の分布を確認しましょう。

tenureという見たことない単語が出てきました。
Googleさんによると「在職期間」ということなのですが、お客さんとして登録されている期間という意味合いでしょう、たぶん。
「客である期間」と「支出額」の分布を見てみよう。
昔からのお客さんは今までの支出額が多いはずだよね、という仮説に対する検証です。

セル9(Python)

import matplotlib.pyplot as plt
import pandas as pd
from snowflake.snowpark import DataFrame as SnowparkDataFrame

# On runtime >=2.6 SQL cell results are returned as Snowpark DataFrames that need to be converted to pandas DataFrames
# On runtime <2.6 SQL cell results are directly returned as pandas DataFrames
# For more details, see https://docs.snowflake.com/en/developer-guide/snowflake-ml/container-runtime/releases
df = dataframe_1.to_pandas() if isinstance(dataframe_1, SnowparkDataFrame) else dataframe_1.copy()

df['SIGNUP_DATE'] = pd.to_datetime(df['SIGNUP_DATE'])
df['days_since_signup'] = (pd.Timestamp.today() - df['SIGNUP_DATE']).dt.days
df = df.sort_values('days_since_signup')

plt.figure(figsize=(10, 6))
plt.scatter(df['days_since_signup'], df['LIFETIME_VALUE'], alpha=0.3)
plt.plot(df['days_since_signup'], df['LIFETIME_VALUE'].rolling(100).mean(), color='red', linewidth=2, label='Rolling Avg')

plt.xlabel("Days Since Signup")
plt.ylabel("Lifetime Value")
plt.title("Customer Tenure vs Spend")
plt.legend()
plt.show()
  1. dataframe_1 を pandas に変換
  2. 登録日から「何日経過したか」を計算
  3. 散布図(各顧客を点でプロット)+ ローリング平均(赤い線)を描画
    をやってます。

セル10(Markdown)

Congrats! Now create your own! ✅

Click "Create file" in a workspace and select Notebooks.

Resources to help you get started

おめでとう!あとは自分で作ってみてね。という締めのお言葉。

実行

いよいよ左上の実行ボタンを押します。

セル3(Python)

!pip freeze # Shows all pre-installed packages

結果出力はめちゃくちゃたくさんあるので畳んでおきます。

出力結果 absl-py==2.4.0 accelerate==1.14.0 aiobotocore==2.26.0 aiohappyeyeballs==2.6.2 aiohttp==3.14.1 aiohttp-cors==0.8.1 aioitertools==0.13.0 aiosignal==1.4.0 annotated-doc==0.0.4 annotated-types==0.7.0 anyio==4.14.0 anywidget==0.11.0 appdirs==1.4.4 argon2-cffi==25.1.0 argon2-cffi-bindings==25.1.0 arrow==1.4.0 arviz==1.2.0 arviz-base==1.2.0 arviz-plots==1.2.0 arviz-stats==1.2.0 asn1crypto==1.5.1 asttokens==3.0.1 async-lru==2.3.0 attrs==26.1.0 babel==2.18.0 bayesian-optimization==1.5.1 beautifulsoup4==4.15.0 better_optimize==0.4.2 bleach==6.4.0 blinker==1.9.0 boto3==1.41.5 botocore==1.41.5 cachetools==5.5.2 CausalPy==0.8.0 certifi==2026.5.20 cffi==2.0.0 charset-normalizer==3.4.7 click==8.2.1 clikit==0.6.2 cloudpickle==3.1.1 cmdstanpy==1.3.0 colorama==0.4.6 colorful==0.5.8 comm==0.2.3 cons==0.4.7 contourpy==1.3.3 crashtest==0.3.1 cryptography==49.0.0 cycler==0.12.1 datasets==5.0.0 datasketches==5.2.0 debugpy==1.8.21 decorator==5.3.1 deepdiff==8.6.2 defusedxml==0.7.1 dill==0.4.1 distlib==0.4.3 etuples==0.3.10 evaluate==0.4.6 executing==2.2.1 fastapi==0.137.1 fastjsonschema==2.21.2 filelock==3.29.4 FLAML==2.6.0 Flask==3.1.3 fonttools==4.63.0 fqdn==1.5.1 frozenlist==1.8.0 fsspec==2025.12.0 gcsfs==2025.12.0 geojson==3.3.0 google-api-core==2.31.0 google-auth==2.55.0 google-auth-oauthlib==1.4.0 google-cloud-core==2.6.0 google-cloud-storage==3.12.0 google-cloud-storage-control==1.12.0 google-crc32c==1.8.0 google-resumable-media==2.10.0 googleapis-common-protos==1.75.0 graphviz==0.21 grpc-google-iam-v1==0.14.4 grpcio==1.78.0 grpcio-status==1.78.0 gunicorn==25.0.3 h11==0.16.0 h2==4.3.0 hf-xet==1.5.1 holidays==0.99 hpack==4.1.0 httpcore==1.0.9 httpstan==4.13.0 httpx==0.28.1 huggingface_hub==0.36.2 hyperframe==6.1.0 idna==3.18 importlib_resources==6.5.2 inflection==0.5.1 ipykernel==7.3.0 ipython==9.14.1 ipython_pygments_lexers==1.1.1 ipywidgets==8.1.8 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.20.0 Jinja2==3.1.6 jmespath==1.1.0 joblib==1.5.3 jpype1==1.7.1 json5==0.14.0 jsonpointer==3.1.1 jsonschema==4.26.0 jsonschema-specifications==2025.9.1 jupyter-events==0.12.1 jupyter_client==8.9.1 jupyter_core==5.9.1 jupyter_server==2.19.0 jupyter_server_terminals==0.5.4 jupyterlab==4.5.8 jupyterlab_pygments==0.3.0 jupyterlab_server==2.28.0 jupyterlab_widgets==3.0.16 kiwisolver==1.5.0 lark==1.3.1 lazy-loader==0.5 lightgbm==4.6.0 lightgbm-ray==0.1.9 llvmlite==0.47.0 logical-unification==0.4.7 markdown-it-py==4.2.0 MarkupSafe==3.0.3 marshmallow==3.26.2 matplotlib==3.11.0 matplotlib-inline==0.2.2 mdurl==0.1.2 miniKanren==1.0.5 mistune==3.2.1 mlruntimes_service==2.7.35 modin==0.37.1 mpmath==1.3.0 msgpack==1.2.0 multidict==6.7.1 multipledispatch==1.0.0 multiprocess==0.70.19 mypy_extensions==1.1.0 narwhals==2.22.1 nbclient==0.11.0 nbconvert==7.17.1 nbformat==5.10.4 nest-asyncio2==1.7.2 networkx==3.6.1 nltk==3.9.4 nodeenv==1.10.0 nodejs-wheel-binaries==24.16.0 notebook==7.5.7 notebook_shim==0.2.4 numba==0.65.1 numpy==2.3.5 nvidia-nccl-cu12==2.30.7 oauthlib==3.3.1 opencensus==0.11.4 opencensus-context==0.1.3 openfe==0.0.12 opentelemetry-api==1.42.1 opentelemetry-exporter-otlp-proto-common==1.42.1 opentelemetry-exporter-otlp-proto-grpc==1.42.1 opentelemetry-exporter-prometheus==0.63b1 opentelemetry-proto==1.42.1 opentelemetry-sdk==1.42.1 opentelemetry-semantic-conventions==0.63b1 orderly-set==5.5.0 packaging==25.0 pandapower==3.4.0 pandas==2.3.3 pandera==0.26.1 pandocfilters==1.5.1 parso==0.8.7 pastel==0.2.1 patsy==1.0.2 pexpect==4.9.0 pillow==12.2.0 platformdirs==4.10.0 plotly==6.8.0 polars==1.41.2 polars-runtime-32==1.41.2 preliz==0.26.0 prometheus_client==0.22.1 prompt_toolkit==3.0.52 propcache==0.5.2 prophet==1.3.0 proto-plus==1.28.0 protobuf==6.33.6 psutil==7.2.2 psygnal==0.15.1 ptyprocess==0.7.0 pure_eval==0.2.3 py-spy==0.4.2 py4j==0.10.9.9 pyarrow==24.0.0 pyasn1==0.6.3 pyasn1_modules==0.4.2 pycparser==3.0 pydantic==2.13.4 pydantic_core==2.46.4 Pygments==2.20.0 PyJWT==2.13.0 pylev==1.4.0 pymc==6.0.1 pymc-extras==0.12.1 pyOpenSSL==26.3.0 pyparsing==3.3.2 pyright==1.1.410 pysimdjson==7.0.2 pystan==3.10.1 pytensor==3.0.7 pytensor-distributions==0.2.0 python-dateutil==2.9.0.post0 python-discovery==1.4.2 python-json-logger==4.1.0 pytimeparse==1.1.8 pytz==2026.2 PyYAML==6.0.3 pyzmq==27.1.0 ray==2.55.1 referencing==0.37.0 regex==2026.5.9 requests==2.34.2 requests-oauthlib==2.0.0 retrying==1.4.2 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rfc3987-syntax==1.1.0 rich==15.0.0 rpds-py==2026.5.1 s3fs==2025.12.0 s3transfer==0.15.0 safetensors==0.8.0 scikit-learn==1.7.2 scipy==1.15.3 seaborn==0.13.2 Send2Trash==2.1.0 sentencepiece==0.2.1 server-extensions @ file:///extensions/server_extensions setuptools==82.0.1 shap==0.52.0 six==1.17.0 slicer==0.0.8 smart_open==7.6.1 snowflake==1.12.1 snowflake-connector-python==4.6.0 snowflake-ml-python==1.42.0 snowflake-notebook-utils @ file:///extensions/snowflake_notebook_utils snowflake-snowpark-python==1.52.0 snowflake._legacy==1.0.2 snowflake.core==1.12.1 snowpark-connect==1.30.0 snowpark-connect-deps-1==3.56.5 snowpark-connect-deps-2==3.56.5 sortedcontainers==2.4.0 soupsieve==2.8.4 sqlglot==30.11.0 sqlparse==0.5.5 stack-data==0.6.3 stanio==0.5.1 starlette==1.3.1 statsmodels==0.14.6 sympy==1.13.1 terminado==0.18.1 threadpoolctl==3.6.0 tinycss2==1.5.1 tokenizers==0.21.4 tomlkit==0.15.0 toolz==1.1.0 torch==2.6.0+cpu torchvision==0.21.0+cpu tornado==6.5.7 tqdm==4.68.2 traitlets==5.15.1 transformers==4.51.3 typeguard==4.5.2 typing-inspect==0.9.0 typing-inspection==0.4.2 typing_extensions==4.15.0 tzdata==2026.2 tzlocal==5.4 uri-template==1.3.0 urllib3==2.7.0 uvicorn==0.49.0 virtualenv==21.5.0 wcwidth==0.8.1 webargs==8.7.1 webcolors==25.10.0 webencodings==0.5.1 websocket-client==1.9.0 Werkzeug==3.1.8 wheel==0.47.0 widgetsnbextension==4.0.15 wrapt==1.17.3 xarray==2026.4.0 xarray-einstats==0.10.0 xgboost==3.2.0 xgboost-ray==0.1.19 xxhash==3.7.0 yarl==1.24.2

セル5(SQL)

select
  seq4() as customer_id,
  'customer_' || (customer_id + 1) as name,
  'customer_' || (customer_id + 1) || '@example.com' as email,
  dateadd(day, -uniform(0, 3650, random()), current_date()) as signup_date,
  round(uniform(100, 100000, random()) / 100, 2) as lifetime_value
from table(generator(rowcount => 1000));

1,000行のデータ生成結果
image.png

セル7(SQL)

SELECT * FROM {{dataframe_1}} WHERE "LIFETIME_VALUE" > 800;

セル5で生成した1,000件が入っているdataframe_1からLTVが800以上のSELECTした結果
image.png
197レコード取得できました。

セル9(Python)

import matplotlib.pyplot as plt
import pandas as pd
from snowflake.snowpark import DataFrame as SnowparkDataFrame

# On runtime >=2.6 SQL cell results are returned as Snowpark DataFrames that need to be converted to pandas DataFrames
# On runtime <2.6 SQL cell results are directly returned as pandas DataFrames
# For more details, see https://docs.snowflake.com/en/developer-guide/snowflake-ml/container-runtime/releases
df = dataframe_1.to_pandas() if isinstance(dataframe_1, SnowparkDataFrame) else dataframe_1.copy()

df['SIGNUP_DATE'] = pd.to_datetime(df['SIGNUP_DATE'])
df['days_since_signup'] = (pd.Timestamp.today() - df['SIGNUP_DATE']).dt.days
df = df.sort_values('days_since_signup')

plt.figure(figsize=(10, 6))
plt.scatter(df['days_since_signup'], df['LIFETIME_VALUE'], alpha=0.3)
plt.plot(df['days_since_signup'], df['LIFETIME_VALUE'].rolling(100).mean(), color='red', linewidth=2, label='Rolling Avg')

plt.xlabel("Days Since Signup")
plt.ylabel("Lifetime Value")
plt.title("Customer Tenure vs Spend")
plt.legend()
plt.show()

描画結果
image.png

全然相関がないwww
1,000件のデータ生成時に、この辺とくに手心加えずにuniform()、random()で作ってましたからね。
データの生成は肝心です。

まとめ

データがランダムすぎて分析としては結果が得られませんでした。
でもSnowflakeのノートブックの使い方は完全に理解した。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?