はじめに
Jupyter Notebookを「ただのセル実行ツール」として使っていませんか?
実はマジックコマンドや拡張機能を活用すれば、生産性が劇的に向上するよ。
マジックコマンド編
1. %timeit - 実行時間計測
%timeit sum(range(10000))
# 187 µs ± 2.74 µs per loop
%timeit sum([i for i in range(10000)])
# 378 µs ± 5.12 µs per loop
複数行は %%timeit:
%%timeit
total = 0
for i in range(10000):
total += i
2. %time - 1回だけ計測
%time result = heavy_computation()
# CPU times: user 1.23 s, sys: 45.6 ms, total: 1.28 s
# Wall time: 1.31 s
3. %run - 外部スクリプト実行
%run my_script.py
%run -i my_script.py # 現在の名前空間で実行
4. %load - ファイル内容をセルに読み込み
%load utils.py
# 実行すると utils.py の内容がセルに展開される
5. %who / %whos - 変数一覧
%who # 変数名のみ
%whos # 型とサイズも表示
%who str # str型の変数のみ
Variable Type Data/Info
-----------------------------
df DataFrame 1000 rows × 5 columns
model RandomForestClassifier ...
result dict n=3
6. %reset - 名前空間リセット
%reset -f # 確認なしでリセット
7. %%writefile - セル内容をファイルに保存
%%writefile utils.py
def helper():
return "Hello"
8. %env - 環境変数
%env API_KEY=secret123
%env API_KEY # 確認
9. %matplotlib inline / %matplotlib widget
%matplotlib inline # 静的グラフ(定番)
%matplotlib widget # インタラクティブ(ipympl必要)
10. %%capture - 出力をキャプチャ
%%capture captured
print("This won't show")
# 後で captured.stdout で取得可能
11. %prun - プロファイリング
%prun heavy_function()
ncalls tottime percall cumtime percall filename:lineno(function)
1000 0.567 0.001 1.234 0.001 module.py:42(inner_func)
12. %debug - デバッガ起動
# エラー発生後に実行
%debug
ショートカット編
| キー | 動作 |
|---|---|
Shift + Enter |
セル実行して次へ |
Ctrl + Enter |
セル実行(その場) |
Alt + Enter |
セル実行して下に挿入 |
Esc → A
|
上にセル挿入 |
Esc → B
|
下にセル挿入 |
Esc → DD
|
セル削除 |
Esc → M
|
Markdownに変換 |
Esc → Y
|
コードに変換 |
Ctrl + Shift + - |
セル分割 |
Tab |
コード補完 |
Shift + Tab |
ドキュメント表示 |
シェルコマンド
!pip install pandas # シェルコマンド
!ls -la
files = !ls *.csv # 変数に代入
print(files)
出力表示のカスタマイズ
DataFrameの表示設定
import pandas as pd
pd.set_option('display.max_columns', None) # 全列表示
pd.set_option('display.max_rows', 100) # 最大100行
pd.set_option('display.width', None) # 幅制限なし
pd.set_option('display.precision', 3) # 小数点3桁
複数出力
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# これで最後だけでなく全ての式が表示される
df.head()
df.describe() # 両方表示される
便利な拡張機能
nbextensions
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
おすすめ拡張:
- Table of Contents: 目次自動生成
- ExecuteTime: 実行時間表示
- Autopep8: コード整形
- Variable Inspector: 変数ビューア
- Collapsible Headings: セクション折りたたみ
テーマ変更
pip install jupyterthemes
jt -t monokai -f fira -fs 12 # Monokaiテーマ
jt -r # リセット
進捗バー(tqdm)
from tqdm.notebook import tqdm
import time
for i in tqdm(range(100), desc="Processing"):
time.sleep(0.01)
自動保存設定
%autosave 60 # 60秒ごとに自動保存
カスタムマジックの作成
from IPython.core.magic import register_line_magic
@register_line_magic
def hello(line):
return f"Hello, {line}!"
%hello World
# 'Hello, World!'
JupyterLab vs Notebook
| 機能 | Notebook | JupyterLab |
|---|---|---|
| ファイルブラウザ | 別タブ | 統合 |
| タブ | なし | あり |
| 拡張機能 | nbextensions | labextensions |
| ダークモード | テーマ必要 | 標準搭載 |
| ターミナル | 別途 | 統合 |
2025年は JupyterLab 推奨です。
VS Code の Jupyter
VS Codeの「Jupyter」拡張機能もおすすめ:
- IntelliSense(コード補完)が強力
- Git連携がスムーズ
- デバッガが使える
まとめ
| カテゴリ | よく使う機能 |
|---|---|
| 計測 |
%timeit, %time
|
| デバッグ |
%debug, %prun
|
| 変数 |
%whos, %reset
|
| 外部連携 |
%run, !command
|
| 出力 |
%%capture, %%writefile
|
知ってると知らないで生産性が全然違います。
まずは %timeit と %whos から使ってみてください!