Skip to main content

SnowflakeのNotebookでStreamlitを使う方法

notebook_cover_image

Image by Jan from Pixabay

データ分析において、結果を分かりやすく可視化し、共有することは非常に重要です。従来のBIツールに加えて、近年ではインタラクティブなデータアプリが注目されています。

Snowflake で Notebook と Streamlit を使えるのを知っていますか? Notebook の中で Streamlit を使えるのも知っていますか?

SnowflakeノートブックとStreamlitを使えば、Pythonの知識だけで、簡単にインタラクティブなデータアプリを作成できます。Snowflakeノートブックは、コード、Markdownによる説明、そして可視化結果を1つのドキュメントにまとめることができるため、データ分析の作業効率を向上させます。

この記事では、Snowflakeノートブック上でStreamlitを使ってインタラクティブなデータアプリを作成する方法を紹介します。SQLクエリからデータを取得し、Streamlitのコンポーネントを使って動的なグラフや入力フォームを備えたアプリを構築する手順を、実際のコード例とともに解説します。

Notebook と Streamlit は何でしょう?

Notebook
ノートブックは、コードとその出力を 1 つのドキュメントに統合し、コード、説明文、視覚化、その他のリッチ メディアを組み合わせることができます。つまり、1 つのドキュメントで、コードを実行し、説明を追加し、出力を表示し、作業をより透明化することができます。
人気なのノートブックはJupyter LabsGoogle Colabです。

Snowflake もノートブックをサポートしています n ので、Snowflake のノートブックではMarkdown, PythonSQLコードを書けます。

notebook_example

内部ノートブックは .ipynb. Interactive Python Notebook (インタラクティブ Python ノートブック) ファイル形式を使用します。

Notebook Extension

Notebook に加えて、Snowflake が Streamlit もサポートしています。

Streamlit
Streamlit を利用したら、Python だけを使ってインタラクティブなウェッブアプリを開発する為に使えます。
つまり、HTML, JavaScript, CSS とかサーバサイドの言語とフレームワークの知識がなくても Streamlit を使ってウェッブアプリを開発出来ます。
Streamlit の概要

Notebookで Streamlit

NotebookでStreamlitを使う事が可能です。

注意点⚠️ :

Notebookで Streamlit のコードを書き、実行するのは可能ですが、もう作成された別の場所である Streamlit のアプリを呼ぶことが出来ないです。

もしもう作成された別の場所である Streamlit のアプリを Notebook の中で使いたいなら、その Streamlit アプリのコードをコピーし、Notebook に paste する必要があります。

Streamlit を使う為に、Streamlit と他の必要なライブラリを以下のようにimportする必要があります。

import streamlit as st

Streamlit を Notebook で使って見ましょう!
以下のコードを実行してみてください。

st.header('Streamlit is working!')
slider = st.slider(label='My Slider', min_value=0, max_value=10)

結果:

python code1

Notebook では python セルが他のセルのデータをアクセ出来ます

他のセルのデータをアクセ出来為に、そのセルのセル名が必要です。
Snowflake が自動的にcell1cell2ようなセル名を生成します。
cell#形も、cells.cell#形も使えます。

もっと進め前に、デモする為に使うデータの準備をしましょう。

dummy_sales_tableと言うテーブルを作成します。

create or replace table dummy_sales_table
(ID integer, Region varchar, Sales integer);

このテーブルにデータを入力します。

insert into dummy_sales_table
values (1, 'China', 100),
 (2, 'Japan', 70),
 (3, 'US', 120),
 (4, 'France', 30),
 (5, 'Germany', 90);

データの確認:

select *
from dummy_sales_table;

sql code1

このクエリーのセル名はcell7です。
このセル名を利用し、python のコードを確認してみましょう。

python code

クエリーの結果を直接に使えないです。使う前に、結果をいずれかPandasDataFrameオブジェクトかSnowparkDataFrameオブジェクトに変える必要があります。

じゃあ、Streamlit を利用し、上のクエリーの結果からグラフを作成しましょう。

# cell7の結果を Pandas dataframeに変える
my_df = cell7.to_pandas()

# Chart the data
st.subheader("Sales in 3 key countries")
st.bar_chart(data=my_df, x='REGION', y='SALES')

python code 3

Python セルのデータを SQL セルで使う方法

Python セルのデータを SQL セルで使う為に、variable 名を SQL セルで {{ variable名 }}として書いてください。

python code4

Streamlit セルのデータを SQL セルで使う方法

Streamlit は Python ライブラリので、Streamlit セルのデータを上にように、{{ variable名 }}、形を使って使います。

table_name = st.selectbox(
    label='見たい例名を選択してください',
    options=['dummy_sales_table', 'some_other_table']
    )

row_count = st.number_input(
    label='見たい行数を入力してください',
    value=1,
    min_value=1,
    max_value=100
    )

結果:

python code5

もし、セルのコードじゃなくて、セルの結果だけを見たいなら、セルの上の右側にアル 2 番目のボタンを押してください。

cell

結果:

python code6

この Streamlit のtable_namerow_countデータを SQL クエリーで使いましょう。

select *
from {{ table_name }}
limit {{ row_count }};

結果:

sql code2

Streamlit はインテラクティブなので、Streamlit のデータの価値が変わったら、Streamlit のセルから下にアル全てのセルが自動的に再実行されります。

python_code7


役に立つリソース

Snowflake についてもっと学びたいなら、以下の記事をご覧ください。

Comments

Popular posts from this blog

Introduction to SQLFluff: How to make your SQL code clean and error-free

Image by Jake Aldridge from Pixabay You know oftentimes, the cause of runtime or compile errors and hours of debugging agony is all due to simply a missing semicolon. Have you ever had such experience? If you had, you are not alone. There are two ways to avoid these unfortunate situations: either become a perfect developer who never makes mistakes, or use helpful tools such as linters that can catch these errors early on. I am nowhere near being a perfect developer who never makes a mistake. In fact, I'm probably the opposite of a perfect developer, so even if I wanted to, I wouldn’t be able to teach you how to become a perfect developer. But what I can teach you is using linters. A Wikipedia defines a linter as a "static code analysis tool used to flag programming errors, bugs, stylistic errors and suspicious constructs." If you're not convinced yet on using linters, consider this scenario: in a large project with multiple members, different people tend to ...

WinMerge のセットアップと使う方

WinMerge は、Windows 用のオープン ソースの差分およびマージ ツールです。WinMerge は、フォルダーとファイルの両方を比較し、違いを理解して扱いやすい視覚的なテキスト形式で表示します。この記事でWinMerge のセットアップと使う方を教えます。 source: https://winmerge.org WinMerge をダウンロード WinMerge のウェブサイト に行って、「WinMerge-2.16.44-x64-Setup.exe」ボタンを押し、WinMerge 2.16 をダウンロードしてください。 WinMerge をインストール ダウンロードされたソフトウェアをクリックし、ポップアップ画面で「Next」を押してください 「Languages」部分をスクロールダウンし、「Japanese menus and dialogs」を選択し、「Next」ボタンを押してください ターミナル等からも WinMerge をアクセス出来ようにする為に「Add WinMerge folder to your system path」オプションを選択し、希望によって他のオプション選択してください 「Enable Explorer context menu Integration」オプションを選択したら、フォルダ/ファイルを右キリックし、コンテクストメニューから WinMerge を開くようになります。 「Install」ボタンを押し、「Next」ボタンを押し、その後、「Finish」ボタンを押してください 言語を日本語にする もし WinMerge の言語が日本語じゃなくて、英語なら、「Edit」タブから「Options」を押してください。 ポップアップ画面で右側の下にある「Languages」と言うドロップダウンメニューから日本語を選択し、「OK」ボタンを押してください WinMerge を使う方 「ファイル」タッブから「開く」を押し 参照ボタンを押し、比較したいフォルダ・ファイルを指定 比較したいフォルダを指定する方法: ポップアップ画面から対象のフォルダーを選択し、「Open」を押してくだい 何も選択しないで、「Open」を押してくだい 右側下にある「比較」ボタンを押し ...

Git squash merge explained

There are many ways to integrate changes in git: regular / normal git merge, git squash merge, git rebase etc. This article explains git squash merge by comparing it to regular merge. Let’s use below example: In the repository with default main branch, after two commits, a new feature branch is created. Some work happened in feature branch. feature branch now has 2 commits that it shares with main branch, and three exclusive commits (exists only in feature branch). In the meantime, others worked on main branch and added two new commits (exists only in main branch). git log output of the main branch: c72d4a9 ( HEAD - > main ) fourth commit on main 2c3dd61 third commit on main 0c2eec3 second commit on main 9b968e8 first commit on main git log output of the feature branch: 786650f ( HEAD - > feature ) third commit on feature 21cbaf1 second commit on feature 677bc7f first commit on feature 0c2eec3 second commit on main 9b968e8 first commit on mai...