๐Ÿ“Š Data Engineering

Jupyter

Jupyter Notebook

An interactive computing environment. Code, results, and documentation in a single notebook. The standard tool of data science.

Detailed Explanation

Jupyter is an open-source platform for interactive computing that integrates code, visualizations, and Markdown documents into a single notebook. It is the de facto standard tool in data science, machine learning, and education.

Jupyter Ecosystem

  • Jupyter Notebook: Classic web-based notebook interface
  • JupyterLab: Next-generation IDE-style interface
  • JupyterHub: Multi-user Jupyter server
  • nbconvert: Converts notebooks to HTML, PDF, slides, and more
  • Voila: Converts notebooks into dashboards

Supported Kernels (Languages)

KernelLanguageUse case
IPythonPythonData Science, ML
IRkernelRStatistical Analysis
IJuliaJuliaScientific Computing
Scala KernelScala/SparkBig Data Processing
IJavascriptJavaScriptWeb Development

Code Example

Notebook Best Practices Template

# =============================================================================
# ๋…ธํŠธ๋ถ ์ œ๋ชฉ: ๊ณ ๊ฐ ์ดํƒˆ ๋ถ„์„
# ์ž‘์„ฑ์ž: Data Team
# ์ž‘์„ฑ์ผ: 2024-01-15
# ๋ชฉ์ : ๊ณ ๊ฐ ์ดํƒˆ ์˜ˆ์ธก ๋ชจ๋ธ ๊ฐœ๋ฐœ ๋ฐ ์ธ์‚ฌ์ดํŠธ ๋„์ถœ
# =============================================================================

# %% [markdown]
# ## 1. ํ™˜๊ฒฝ ์„ค์ • ๋ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ž„ํฌํŠธ
# ๋…ธํŠธ๋ถ ์‹œ์ž‘ ์‹œ ํ•„์š”ํ•œ ๋ชจ๋“  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ํ•œ ๊ณณ์—์„œ ์ž„ํฌํŠธํ•ฉ๋‹ˆ๋‹ค.

# %%
# ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
import os
import sys
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

# ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
import numpy as np
import pandas as pd

# ์‹œ๊ฐํ™”
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('seaborn-v0_8-whitegrid')
plt.rcParams['figure.figsize'] = (12, 6)
plt.rcParams['font.family'] = 'NanumGothic'

# ๋จธ์‹ ๋Ÿฌ๋‹
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix

# ์„ค์ •
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 100)

# ๋žœ๋ค ์‹œ๋“œ ๊ณ ์ • (์žฌํ˜„์„ฑ)
RANDOM_STATE = 42
np.random.seed(RANDOM_STATE)

print(f"Python ๋ฒ„์ „: {sys.version}")
print(f"Pandas ๋ฒ„์ „: {pd.__version__}")
print(f"์‹คํ–‰ ์‹œ๊ฐ„: {datetime.now()}")

# %% [markdown]
# ## 2. ๋ฐ์ดํ„ฐ ๋กœ๋“œ ๋ฐ ๊ธฐ๋ณธ ํƒ์ƒ‰

# %%
# ๋ฐ์ดํ„ฐ ๊ฒฝ๋กœ ์„ค์ • (ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ๋˜๋Š” ์„ค์ • ํŒŒ์ผ ์‚ฌ์šฉ ๊ถŒ์žฅ)
DATA_PATH = os.getenv('DATA_PATH', '../data')

# ๋ฐ์ดํ„ฐ ๋กœ๋“œ
df = pd.read_csv(f'{DATA_PATH}/customer_data.csv')

# ๊ธฐ๋ณธ ์ •๋ณด ํ™•์ธ
print(f"๋ฐ์ดํ„ฐ ํฌ๊ธฐ: {df.shape}")
print(f"\n๋ฐ์ดํ„ฐ ํƒ€์ž…:\n{df.dtypes}")
print(f"\n๊ฒฐ์ธก์น˜:\n{df.isnull().sum()}")

df.head()

# %% [markdown]
# ## 3. ํƒ์ƒ‰์  ๋ฐ์ดํ„ฐ ๋ถ„์„ (EDA)

# %%
# ์ˆ˜์น˜ํ˜• ๋ณ€์ˆ˜ ๊ธฐ์ˆ  ํ†ต๊ณ„
df.describe()

# %%
# ํƒ€๊ฒŸ ๋ณ€์ˆ˜ ๋ถ„ํฌ
fig, ax = plt.subplots(1, 2, figsize=(14, 5))

df['churn'].value_counts().plot(kind='bar', ax=ax[0])
ax[0].set_title('์ดํƒˆ ์—ฌ๋ถ€ ๋ถ„ํฌ')
ax[0].set_xlabel('์ดํƒˆ (1: ์ดํƒˆ, 0: ์œ ์ง€)')

df['churn'].value_counts().plot(kind='pie', autopct='%1.1f%%', ax=ax[1])
ax[1].set_title('์ดํƒˆ ๋น„์œจ')

plt.tight_layout()
plt.show()

# %% [markdown]
# ## 4. ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ

# %%
def preprocess_data(df):
    """๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ํ•จ์ˆ˜ - ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•จ์ˆ˜ํ™”"""
    df_processed = df.copy()

    # ๊ฒฐ์ธก์น˜ ์ฒ˜๋ฆฌ
    df_processed['tenure'].fillna(df_processed['tenure'].median(), inplace=True)

    # ๋ฒ”์ฃผํ˜• ์ธ์ฝ”๋”ฉ
    label_cols = ['gender', 'contract_type']
    for col in label_cols:
        le = LabelEncoder()
        df_processed[col] = le.fit_transform(df_processed[col])

    return df_processed

df_processed = preprocess_data(df)
df_processed.head()

# %% [markdown]
# ## 5. ๋ชจ๋ธ ํ•™์Šต ๋ฐ ํ‰๊ฐ€

# %%
# ํŠน์„ฑ๊ณผ ํƒ€๊ฒŸ ๋ถ„๋ฆฌ
feature_cols = ['tenure', 'monthly_charges', 'total_charges', 'gender', 'contract_type']
X = df_processed[feature_cols]
y = df_processed['churn']

# ํ•™์Šต/ํ…Œ์ŠคํŠธ ๋ถ„ํ• 
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y
)

# ์Šค์ผ€์ผ๋ง
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# ๋ชจ๋ธ ํ•™์Šต
model = RandomForestClassifier(n_estimators=100, random_state=RANDOM_STATE)
model.fit(X_train_scaled, y_train)

# ์˜ˆ์ธก ๋ฐ ํ‰๊ฐ€
y_pred = model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))

# %% [markdown]
# ## 6. ๊ฒฐ๋ก  ๋ฐ ๋‹ค์Œ ๋‹จ๊ณ„
# - ๋ชจ๋ธ ์ •ํ™•๋„: XX%
# - ์ฃผ์š” ์ดํƒˆ ์š”์ธ: tenure, monthly_charges
# - ๋‹ค์Œ ๋‹จ๊ณ„: ํ•˜์ดํผํŒŒ๋ผ๋ฏธํ„ฐ ํŠœ๋‹, ์•™์ƒ๋ธ” ๋ชจ๋ธ ์‹œ๋„

Notebook Automation (papermill)

# papermill์„ ์‚ฌ์šฉํ•œ ๋…ธํŠธ๋ถ ํŒŒ๋ผ๋ฏธํ„ฐํ™” ๋ฐ ์ž๋™ ์‹คํ–‰
import papermill as pm
from datetime import datetime

# ํŒŒ๋ผ๋ฏธํ„ฐํ™”๋œ ๋…ธํŠธ๋ถ ์‹คํ–‰
pm.execute_notebook(
    input_path='analysis_template.ipynb',
    output_path=f'outputs/analysis_{datetime.now().strftime("%Y%m%d")}.ipynb',
    parameters={
        'data_path': '/data/sales_2024.csv',
        'start_date': '2024-01-01',
        'end_date': '2024-01-31',
        'target_metric': 'revenue'
    },
    kernel_name='python3'
)

# ๋ฐฐ์น˜ ์‹คํ–‰ (์—ฌ๋Ÿฌ ํŒŒ๋ผ๋ฏธํ„ฐ ์กฐํ•ฉ)
regions = ['์„œ์šธ', '๋ถ€์‚ฐ', '๋Œ€๊ตฌ', '์ธ์ฒœ']
for region in regions:
    pm.execute_notebook(
        input_path='regional_analysis.ipynb',
        output_path=f'outputs/analysis_{region}.ipynb',
        parameters={'region': region}
    )
    print(f"{region} ๋ถ„์„ ์™„๋ฃŒ")

Using Jupyter Magic Commands

# ์œ ์šฉํ•œ Jupyter ๋งค์ง ์ปค๋งจ๋“œ

# ์…€ ์‹คํ–‰ ์‹œ๊ฐ„ ์ธก์ •
%%time
df.groupby('category').agg({'sales': ['sum', 'mean', 'count']})

# ์ƒ์„ธ ํ”„๋กœํŒŒ์ผ๋ง
%%timeit -n 10 -r 3
result = df.query('sales > 1000')

# ์™ธ๋ถ€ ์Šคํฌ๋ฆฝํŠธ ์‹คํ–‰
%run utils/data_processing.py

# ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ •
%env DATABASE_URL=postgresql://localhost/mydb

# ๋””๋ฒ„๊น…
%debug  # ์—๋Ÿฌ ๋ฐœ์ƒ ํ›„ ๋””๋ฒ„๊ฑฐ ์ง„์ž…

# SQL ์ฟผ๋ฆฌ (ipython-sql ํ™•์žฅ)
%load_ext sql
%sql postgresql://user:pass@localhost/db
%%sql
SELECT * FROM customers LIMIT 10;

# ํŒŒ์ผ ์“ฐ๊ธฐ
%%writefile utils/helper.py
def clean_data(df):
    return df.dropna()

# ๋…ธํŠธ๋ถ ํžˆ์Šคํ† ๋ฆฌ
%history -n 1-10

# ๋ณ€์ˆ˜ ๋ชฉ๋ก
%who_ls DataFrame

# ์‹œ์Šคํ…œ ๋ช…๋ น
!pip install pandas --upgrade
!ls -la data/

Notebook Collaboration Setup (.pre-commit-config.yaml)

# pre-commit hooks for Jupyter notebooks
repos:
  - repo: https://github.com/kynan/nbstripout
    rev: 0.6.1
    hooks:
      - id: nbstripout
        name: Strip notebook outputs

  - repo: https://github.com/nbQA-dev/nbQA
    rev: 1.7.0
    hooks:
      - id: nbqa-black
        name: Format notebook code with black
      - id: nbqa-isort
        name: Sort imports in notebooks
      - id: nbqa-flake8
        name: Lint notebooks with flake8

  - repo: local
    hooks:
      - id: jupyter-nb-clear-output
        name: Clear Jupyter notebook outputs
        entry: jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace
        files: \.ipynb$
        language: system

JupyterHub Configuration (jupyterhub_config.py)

# JupyterHub ๋‹ค์ค‘ ์‚ฌ์šฉ์ž ํ™˜๊ฒฝ ์„ค์ •
c = get_config()

# ์ธ์ฆ ์„ค์ • (LDAP)
from ldapauthenticator import LDAPAuthenticator
c.JupyterHub.authenticator_class = LDAPAuthenticator
c.LDAPAuthenticator.server_address = 'ldap.company.com'
c.LDAPAuthenticator.bind_dn_template = 'uid={username},ou=users,dc=company,dc=com'

# Spawner ์„ค์ • (Docker)
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.DockerSpawner.image = 'jupyter/datascience-notebook:latest'
c.DockerSpawner.network_name = 'jupyterhub-network'

# ๋ฆฌ์†Œ์Šค ์ œํ•œ
c.DockerSpawner.mem_limit = '4G'
c.DockerSpawner.cpu_limit = 2

# ์‚ฌ์šฉ์ž๋ณ„ ๋ณผ๋ฅจ ๋งˆ์šดํŠธ
c.DockerSpawner.volumes = {
    'jupyterhub-user-{username}': '/home/jovyan/work',
    '/data/shared': {'bind': '/home/jovyan/shared', 'mode': 'ro'}
}

# ๊ด€๋ฆฌ์ž ์„ค์ •
c.Authenticator.admin_users = {'admin', 'dataadmin'}

# SSL ์„ค์ •
c.JupyterHub.ssl_cert = '/etc/ssl/certs/jupyterhub.crt'
c.JupyterHub.ssl_key = '/etc/ssl/private/jupyterhub.key'

Practical Conversation Example

Junior Data Analyst: "My kernel keeps dying while I analyze data in a Jupyter notebook. I think it's running out of memory..."
Senior Analyst: "When processing large datasets, read them in chunks or drop unnecessary columns. And try freeing memory with del df; gc.collect() as well."
Junior Data Analyst: "I'm trying to manage notebook files with Git, but conflicts keep happening."
Senior Analyst: "Clear the output cells with nbstripout before committing. Or sync with a .py file using jupytext, which also makes diffs easier to read. If you collaborate a lot, consider JupyterHub or Colab Enterprise."
Junior Data Analyst: "I want to deploy a notebook to production. Is that possible?"
Senior Analyst: "Direct deployment isn't recommended. Refactoring code verified in a notebook into a .py module is fine, and generating automated reports with papermill is acceptable too. For a full-fledged service, use a framework like FastAPI."

Cautions

Reproducibility Issues

  • Cell execution order affects results - verify with Kernel Restart & Run All
  • Fixing the random seed is required (np.random.seed, RANDOM_STATE)
  • Specify environment dependencies (requirements.txt, environment.yml)

Version Control

  • The notebook JSON format makes Git diffs difficult
  • Including output cells causes the repository size to grow sharply
  • Set up pre-commit hooks to automatically remove output cells

Security

  • Do not hardcode API keys or passwords in notebooks
  • Use environment variables or a secrets manager
  • Check for sensitive information before committing to a public repository

Related Terms

Learn More