Skip to content

Pandas チートシート

Python ためのデータ分析と操作のライブラリ。

01

はじめに

インストールとインポート

慣例により pd としてインポートされるのが pandas で、下で numpy 配列を使うため numpy は np です。2 つのコアデータ構造が、Series(1 次元のラベル付き配列)と DataFrame(2 次元のラベル付きテーブル)です。Python でのほとんどすべての表形式のデータ操作が、ここから始まります。

pandas
# Install pandas (pick one)
pip install pandas
conda install pandas

# Standard import convention
import pandas as pd
import numpy as np  # pandas relies heavily on numpy

# Check version
print(pd.__version__)

# Pandas is built on numpy: a Series is a 1D labeled array,
# a DataFrame is a 2D labeled table (dict of Series).

Series と DataFrame

値の 1 列と、インデックス(ラベル)を持つのが、Series です。共通のインデックスを共有する Series のコレクションが、DataFrame です — スプレッドシートか SQL テーブルと考えましょう。dict(キー = 列)、リストのリスト、numpy 配列、ファイルから DataFrame を構築できます。

pandas
import pandas as pd

# Series: 1D labeled array
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
# a    10
# b    20
# ...

# DataFrame: 2D table (dict of columns)
df = pd.DataFrame({
    "name":  ["Alice", "Bob", "Charlie"],
    "age":   [25, 30, 35],
    "city":  ["NYC", "LA", "SF"],
})

# From list of lists with column names
df2 = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"])

サンプル DataFrame の作成

素早い実験のためには、dict から小さい DataFrame を構築しましょう。より大きなテストには、再現性のためにシード付きで、numpy のランダムジェネレータを使います。DatetimeIndex を作るのが、date_range です — 時系列作業の基盤です。早い段階で意味のあるインデックス(日付、ID)を設定すれば、後の選択と結合がはるかにきれいになります。

pandas
import pandas as pd
import numpy as np

# Quick test DataFrame with random data
df = pd.DataFrame({
    "id":     range(1, 6),
    "name":   ["Alice", "Bob", "Charlie", "David", "Eve"],
    "age":    [25, 30, 35, 28, 40],
    "score":  [85.5, 92.0, 78.3, 88.9, 95.2],
    "pass":   [True, True, False, True, True],
})

# Larger random DataFrame
rng = np.random.default_rng(42)
big = pd.DataFrame(rng.normal(size=(100, 4)), columns=list("ABCD"))

# Dates as index
dates = pd.date_range("2024-01-01", periods=5)
ts = pd.DataFrame({"value": [1, 2, 3, 4, 5]}, index=dates)

ファイルからのデータ読み取り

主力が、read_csv です — ロード後の清掃を避けるため、関連する場合 sep、encoding、parse_dates、index_col を必ず指定しましょう。大きな dataset では CSV よりはるかに速く小さく、dtype を保つのが、Parquet です。接続プーリングを扱うのが、SQLAlchemy のエンジンです。素早いコピーペーストの分析に、驚くほど手軽なのが、read_clipboard です。

pandas
import pandas as pd

# CSV — the most common
df = pd.read_csv("data.csv")
df = pd.read_csv("data.csv", sep=";", encoding="utf-8",
                 parse_dates=["date"], index_col="id")

# Excel (needs openpyxl)
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")

# JSON
df = pd.read_json("data.json")

# Parquet (fast columnar format, great for large data)
df = pd.read_parquet("data.parquet")

# SQL (needs SQLAlchemy)
from sqlalchemy import create_engine
engine = create_engine("sqlite:///my.db")
df = pd.read_sql("SELECT * FROM users", engine)

# Clipboard (paste a table from a spreadsheet)
df = pd.read_clipboard()

データの保存

インデックスが意味のあるデータを運ばない限り、CSV/Excel への保存では必ず index=False を渡しましょう — さもないと、再読み込み時に偽の「Unnamed: 0」の列が得られます。save/load をまたいで dtype を保つのが(CSV は失います)、Parquet です。既存の SQL テーブルへ行を加えるのが、if_exists='append' で、上書きが「replace」です。

pandas
import pandas as pd

# CSV (no index by default is usually what you want)
df.to_csv("output.csv", index=False)
df.to_csv("output.csv", index=False, encoding="utf-8-sig")  # Excel-friendly

# Excel (needs openpyxl)
df.to_excel("output.xlsx", sheet_name="Sheet1", index=False)

# Parquet (preserves dtypes, fast, compressed)
df.to_parquet("output.parquet")

# JSON
df.to_json("output.json", orient="records", indent=2)

# SQL
df.to_sql("users", engine, if_exists="replace", index=False)

# Multiple sheets to one Excel file
with pd.ExcelWriter("multi.xlsx") as writer:
    df1.to_excel(writer, sheet_name="sheet1", index=False)
    df2.to_excel(writer, sheet_name="sheet2", index=False)
02

データの検査

データの閲覧:head、tail、sample

端を示すのが head/tail で、ランダムな行を示すのが sample です。後者の方が、分布と形式の整合性確認には代表的です。幅広の DataFrame を検査するときは、切り詰めを無効化するのに set_option を使いましょう — デフォルトが、列と行を隠します。エンコーディング問題、センチネル値、型の不一致を早く捉えるため、分析の前に必ずサンプルデータを見ましょう。

pandas
import pandas as pd

# First/last rows
df.head()        # first 5 (default)
df.head(10)      # first 10
df.tail()        # last 5
df.tail(3)       # last 3

# Random sample (great for sanity checks)
df.sample(5)                    # 5 random rows
df.sample(frac=0.1, random_state=42)  # 10% of rows
df.sample(n=5, replace=True)    # sample with replacement (bootstrap)

# See the raw values (not truncated)
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 1000)

構造と Dtype

最も有用な単一の検査呼び出しが、info() です — dtype、列ごとの非 null の数、メモリを示します。注意するのが、object の dtype です(通常、非効率的に保存された文字列)。「category」か「string」の dtype への変換がメモリを節約します。オブジェクトの列の本物のコストを明らかにするのが、memory_usage(deep=True) です。これはしばしば報告よりはるかに大きいです。

pandas
# Shape and basic structure
df.shape         # (rows, cols)
df.size          # rows * cols
df.ndim          # 2 for DataFrame, 1 for Series
len(df)          # number of rows

# Column names and dtypes
df.columns       # column labels
df.index         # row labels
df.dtypes        # dtype of each column
df.info()        # concise summary: dtypes, non-null counts, memory

# Memory usage (helpful for big data)
df.memory_usage(deep=True)
df.info(memory_usage="deep")

記述統計

速い統計の要約を与えるのが、describe() です — 不一致な count(欠損値)と、疑わしい min/max に注意しましょう。カテゴリの列には不可欠なのが、value_counts() です(頻度とクラスバランスを示します)。Pearson が corr() のデフォルトで、ランク相関には method='spearman' を。混合型のフレーム上では、エラーを避けるため必ず numeric_only=True を使いましょう。

pandas
# Numeric summary (count, mean, std, min, quartiles, max)
df.describe()
df.describe(include="all")   # include non-numeric too
df.describe(percentiles=[.1, .5, .9])

# Per-column stats
df["age"].mean()
df["age"].median()
df["age"].std()
df["age"].var()
df["age"].min(), df["age"].max()
df["age"].quantile(0.95)

# Non-numeric summaries
df["city"].value_counts()
df["city"].unique()
df["city"].nunique()

# Correlation and covariance
df.corr(numeric_only=True)
df.cov(numeric_only=True)

一意の値とカウント

最もよく使われる pandas のメソッドの一つが、value_counts です。比率のためには normalize=True と、欠損の確認のためには dropna=False とペアにしましょう。2 つのカテゴリの頻度表を作るのが、crosstab で、カイ二乗テストと混同行列に有用です。value_counts の前の連続列のビニングが、分布の形状を明らかにします。

pandas
# Unique values
df["city"].unique()              # array of unique values
df["city"].nunique()             # count of unique
df["city"].nunique(dropna=False) # include NaN

# Value counts (frequency table)
df["city"].value_counts()
df["city"].value_counts(normalize=True)   # proportions
df["city"].value_counts(ascending=True)
df["city"].value_counts(dropna=False)     # count NaN too

# Cross tabulation (frequency table of two columns)
pd.crosstab(df["city"], df["pass"])

# Binning then counting
df["age_group"] = pd.cut(df["age"], bins=[0, 18, 30, 50, 100],
                          labels=["child", "young", "adult", "senior"])
df["age_group"].value_counts()

欠損値の確認

分析の前に必ず欠損を確認しましょう — 列ごとの isnull().sum() が、標準の最初の見方です。高い欠損割合を持つ列に注意しましょう。削除か、異なる処理戦略が必要かもしれません。重要な列に欠損値のある行は、df[df.isnull().any(axis=1)] でフィルタできます。欠損パターンを可視化し構造的なデータ問題を発見するのが、missingno ライブラリです。

pandas
# Count missing per column
df.isnull().sum()
df.isna().sum()           # alias

# Fraction missing
df.isnull().mean().mul(100).round(2)  # % missing per column

# Total missing
df.isnull().sum().sum()

# Rows with any missing
df[df.isnull().any(axis=1)]

# Non-null counts
df.notnull().sum()

# Visualize missingness pattern
# (requires missingno: import missingno as msno; msno.matrix(df))
03

Series の基本

Series の作成

ラベル(インデックス)を持つ 1 次元配列が、Series です。位置だけでなくラベルによる値の参照を可能にするのが、インデックスです。大きなデータでのメモリ節約のため、より小さい dtype(int8、float32)を指定しましょう — -128..127 を保持するのが int8 で、int としての真偽値か小さいコードには十分です。自然にインデックスになるのが、dict のキーです。

pandas
import pandas as pd
import numpy as np

# From a list
s = pd.Series([1, 2, 3, 4])

# From a list with custom index
s = pd.Series([10, 20, 30], index=["a", "b", "c"])

# From a dict (keys become index)
s = pd.Series({"a": 1, "b": 2, "c": 3})

# From a numpy array
s = pd.Series(np.random.randn(5))

# Scalar broadcast to an index
s = pd.Series(5, index=["a", "b", "c"])  # [5, 5, 5]

# Specify dtype
s = pd.Series([1, 2, 3], dtype="float64")
s = pd.Series([1, 2, 3], dtype="int8")    # save memory

インデックスと選択

(排他的な)Python の位置的なスライスと違い、(両端で「含む」)のが、ラベルベースのスライス(s['a':'c'])です — よくある落とし穴です。曖昧さを避けるため、ラベルには .loc を、位置には .iloc を使いましょう(整数インデックスでは特に)。オーバーロードされているのが、デフォルトの s[...] です(dtype によりラベルか位置)。そのため、本番コードでは明示的な .loc/.iloc がより安全です。

pandas
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])

# By label (index)
s["a"]            # 10
s[["a", "c"]]     # multiple labels -> Series
s["a":"c"]        # slice INCLUSIVE of both ends (label-based)

# By position
s.iloc[0]         # first by position
s.iloc[-1]        # last
s.iloc[1:3]       # EXCLUSIVE of end (positional, like Python)

# By label with .loc (explicit)
s.loc["a"]
s.loc["a":"c"]    # inclusive

# Boolean indexing
s[s > 20]
s[(s > 10) & (s < 40)]

ベクトル化された操作

ベクトル化される(Python のループなし)のが、Series 上の操作であり、インデックス上で整列します — 2 つの Series を加えるとき、pandas がラベルをマッチし、ラベルが重ならない所に NaN を満たします。pandas の決定的な機能が、このインデックスの整列ですが、驚くことがあり得ます。純粋に位置的な数学を望むなら、生の numpy 配列上で操作するには .values を。iterrows のループより 100〜1000 倍速いのが、ベクトル化された操作です。

pandas
s = pd.Series([1, 2, 3, 4])

# Element-wise arithmetic (aligns on index)
s + 10          # [11, 12, 13, 14]
s * 2
s ** 2
1 / s           # [1.0, 0.5, 0.333, 0.25]

# Between two Series (aligns on index, NaN for mismatches)
s1 = pd.Series({"a": 1, "b": 2, "c": 3})
s2 = pd.Series({"b": 20, "c": 30, "d": 40})
s1 + s2         # a=NaN, b=22, c=33, d=NaN

# Comparison and boolean
s > 2           # [False, False, True, True]
s.between(2, 3) # inclusive

# Math methods
s.sum(), s.mean(), s.std(), s.cumsum()

有用な Series のメソッド

日常の道具が、sort_values と rank です。デフォルトで最初の発生を保つのが、drop_duplicates で、最後には keep='last' を。プロット前のはずれ値の上限に便利なのが、clip です。デフォルトで NaN をスキップするのが、ほとんどのメソッドで、NaN を伝播させるには skipna=False を渡しましょう。新しい Series を返すのが、多くのメソッドであるため(pandas がほとんど不変)、チェーンさせましょう:s.dropna().sort_values().head(10)。

pandas
s = pd.Series([3, 1, 4, 1, 5, 9, 2, 6, np.nan])

# Sorting
s.sort_values()                  # ascending
s.sort_values(ascending=False)
s.sort_index()

# Ranking
s.rank(method="average")         # 'min','max','first','dense'

# Unique, counts
s.unique()
s.nunique()
s.value_counts()
s.duplicated()                   # boolean: True if seen before
s.drop_duplicates()

# Statistical
s.sum(), s.prod(), s.cumsum(), s.cummax()
s.abs()
s.round(2)
s.clip(lower=0, upper=10)        # cap values to a range
s.quantile([0.25, 0.5, 0.75])

Series での NaN の処理

多くの戦略を fillna が持ちます:定数、統計(平均/中央値)、前/後方の充填(時系列に最適)、補間です。最後に知られた値を伝播させるのが、ffill/bfill で — ジャンプすべきでないセンサーや株のデータに理想的です。読み取り時には、センチネル('?'、-999)を一様に扱われる NaN へ変換するのが、na_values です。linear、time、index ベースのメソッドに対応するのが、interpolate です。

pandas
s = pd.Series([1.0, 2.0, np.nan, 4.0, np.nan])

# Detect
s.isna()             # boolean mask
s.notna()
s.isna().sum()       # count of NaN

# Drop
s.dropna()           # remove NaN

# Fill
s.fillna(0)                       # constant
s.fillna(s.mean())                # with mean
s.fillna(method="ffill")          # forward fill (old API)
s.ffill()                         # forward fill (new)
s.bfill()                         # backward fill
s.interpolate()                   # linear interpolation

# Replace sentinel values with NaN on read
# pd.read_csv("x.csv", na_values=["?", "N/A", ""])
04

選択とフィルタリング

列の選択

常に機能するのが、括弧の記法 df['col'] で、便利なのが、ドットの記法 df.col ですが、スペースのある名前や、メソッド(「count」のような)と衝突する名前では失敗します。各名前を列挙せず列のグループを取るきれいな方法が、filter(like=) と select_dtypes です — 何百もの列を持つ幅広の DataFrame では非常に有用です。

pandas
# Single column (returns Series)
df["age"]
df.age            # only if name is a valid Python identifier

# Multiple columns (returns DataFrame)
df[["name", "age", "city"]]

# Columns by pattern
df.filter(like="age")               # columns containing "age"
df.filter(regex="^\d{4}$")          # columns matching regex
df.filter(items=["name", "age"])    # specific columns

# Select by dtype
df.select_dtypes(include="number")
df.select_dtypes(include=["int64", "float64"])
df.select_dtypes(exclude="object")
df.select_dtypes(include="datetime")

loc 対 iloc

第 1 の pandas の落とし穴:.loc がラベルを使い(含むスライス)、.iloc が位置を使います(排他的スライス)。代入のためには、ALWAYS で .loc/iloc を使いましょう — df[df.a<5]['b']=0 のようなチェーンされたインデックスが、SettingWithCopyWarning を出し、静かに失敗し得ます。ラベルベースのフィルタリングをサポートするのが、真偽マスク付きの .loc で、フィルタと代入のきれいな方法です。

pandas
# .loc: label-based (inclusive slices)
df.loc[5]                         # row with index label 5
df.loc[5, "name"]                 # row 5, column 'name'
df.loc[5:10, ["name", "age"]]     # rows 5-10 (inclusive), 2 cols
df.loc[df["age"] > 30]            # boolean mask

# .iloc: position-based (exclusive slices)
df.iloc[0]                        # first row
df.iloc[-1]                       # last row
df.iloc[0:5]                      # first 5 rows (exclusive)
df.iloc[0:5, 0:2]                 # first 5 rows, first 2 cols
df.iloc[:, 0]                     # all rows, first column

# Setting values (use .loc for assignment!)
df.loc[df["age"] < 0, "age"] = 0  # cap negatives to 0

# AVOID chained indexing: df[df["a"]<5]["b"] = 0  # SettingWithCopyWarning

真偽値のフィルタリング

条件を組み合わせるときは、各条件の周りに括弧付きで & | ~ を使いましょう — 真偽値配列上では、Python の and/or が機能しません。複数の値によるフィルタのきれいな方法が、isin です(チェーンされた == より速い)。.str アクセサを使うのが、文字列のフィルタリングです。否定するのが、~(bitwise NOT)です。新しいフィルタ済みの DataFrame を返すのが、これらすべてで、保持するには変数へ代入しましょう。

pandas
# Single condition
df[df["age"] > 30]
df[df["city"] == "NYC"]

# Multiple conditions (use & | ~, NOT and/or/not; parenthesize!)
df[(df["age"] > 25) & (df["city"] == "NYC")]
df[(df["city"] == "NYC") | (df["city"] == "LA")]
df[~df["pass"]]                       # NOT pass

# isin for membership
df[df["city"].isin(["NYC", "LA", "SF"])]

# String methods in filters
df[df["name"].str.startswith("A")]
df[df["name"].str.contains("li", case=False)]

# Between
df[df["age"].between(25, 35, inclusive="both")]

# Null checks
df[df["score"].isnull()]
df[df["score"].notnull()]

query() メソッド

SQL のように読め、真偽値インデックスの「どこにでも括弧」の必要性を避けるのが、query() です。ローカルの Python 変数を参照するには、@ を使いましょう。大きな DataFrame では、query がより速くなり得ます。numexpr で式を評価し、中間の真偽配列の作成を避けるからです。groupby のチェーンとパイプラインの中で特に良いです。

pandas
# query() — string-based filtering, often more readable
df.query("age > 30")
df.query("age > 25 and city == 'NYC'")
df.query("age > 25 and city in ['NYC', 'LA']")
df.query("age > 25 or score > 90")

# Refer to Python variables with @
cities = ["NYC", "LA"]
df.query("city in @cities")

# Compare columns
df.query("score > age")

# Negation
df.query("not pass")

# query is faster than boolean indexing on large frames
# because it uses numexpr to avoid intermediate arrays

サンプリングとサンプリング重み

元のインデックスを保つきれいな train/test 分割が、sample(frac=0.8) と、その後の drop(train.index) です。層化サンプリング(クラス比率を保つ)には、手動の pandas コードより信頼できるのが、sklearn の train_test_split です。重要度サンプリングや、偏ったデータのシミュレーションに有用なのが、重み付きのサンプリングです。

pandas
# Random sample
df.sample(n=5)                          # 5 rows
df.sample(frac=0.1)                     # 10% of rows
df.sample(n=5, random_state=42)         # reproducible

# Sample with weights
df.sample(n=5, weights="score")         # higher score -> more likely

# Sample with replacement (bootstrap)
df.sample(n=len(df), replace=True)

# Train/test split
train = df.sample(frac=0.8, random_state=42)
test = df.drop(train.index)

# Stratified sample (preserve class proportions)
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.2,
                                stratify=df["city"], random_state=42)
05

データのクリーンアップ

欠損データの処理

完全に空の行だけを落とすのが、dropna(how='all') で、少なくとも N 個の非 null 値を持つ行を保つのが、thresh です。複数の fillna 呼び出しよりきれいなのが、dict による列ごとの充填です。時系列には、連続性を保つのが、ffill/bfill と interpolate です。欠損自体が情報を持つか考慮する必要が必ずあり — 補完の前に「is_missing」のインジケータ列を加えれば、その信号が ML のために保たれます。

pandas
# Drop rows with any missing
df.dropna()                       # any NaN in any column
df.dropna(how="all")              # only if ALL columns NaN
df.dropna(subset=["age", "city"]) # only check these columns
df.dropna(thresh=3)               # keep rows with >=3 non-NaN

# Fill missing
df.fillna(0)
df.fillna({"age": df["age"].mean(),
           "city": "Unknown"})
df["age"] = df["age"].fillna(df["age"].median())

# Forward/backward fill (for time series)
df.ffill()
df.bfill()

# Interpolate
df.interpolate(method="linear")
df.interpolate(method="time")     # for DatetimeIndex

# Flag rows that were imputed
df["age_was_missing"] = df["age"].isnull()

重複の除去

以前の行を繰り返す行を印付けるのが、duplicated() で、代わりに最初の発生を印付けるのが、keep='last' です。すべての重複行(最初を含む)を印付けるのが、keep=False で、衝突するすべての行を検査したいときに有用です。新しい DataFrame を返すのが、drop_duplicates で、修正するには inplace=True を渡すか再代入しましょう。email や ID のようなキーの列での重複除去を可能にするのが、subset です。

pandas
# Find duplicates
df.duplicated()                   # True for rows that are duplicates of earlier
df.duplicated().sum()             # count
df[df.duplicated()]               # view duplicates

# Drop duplicates
df.drop_duplicates()              # full-row duplicates
df.drop_duplicates(subset=["email"])   # dup on email only
df.drop_duplicates(subset=["name", "dob"], keep="last")  # keep last occurrence
df.drop_duplicates(keep=False)    # drop ALL duplicates (keep none)

# Find rows where a column is duplicated
df[df.duplicated(subset=["email"], keep=False)]
# .keep=False marks ALL duplicates (including first)

改名と並べ替え

改名の最も安全な方法が、columns の dict 付きの rename です — 列挙された列だけを改名し、他には触れません。望む順での選択が、列の並べ替えにすぎません。乱れたインデックスを置き換えるきれいな方法が、set_index の後の reset_index(drop=True) です。列名には早く str.strip を使いましょう — 見えない末尾スペースが、終わりのない「KeyError」の頭痛の原因になります。

pandas
# Rename columns
df.rename(columns={"old_name": "new_name"})
df.rename(columns=str.upper)        # uppercase all
df.rename(columns=str.strip)        # strip whitespace

# Replace all column names
df.columns = ["id", "name", "age"]

# Add prefix/suffix
df.add_prefix("col_")
df.add_suffix("_v2")

# Reorder columns
df[["name", "age", "city"]]          # select in new order

# Reorder rows by index
df.sort_index()

# Reset / set index
df.reset_index(drop=True)            # drop old index
df.set_index("id")                   # use 'id' as index

# Swap rows and columns
df.transpose()  # or df.T

型の変換

パースできない値で失敗するのが、astype です。代わりに、悪い値を NaN へ変えるのが、errors='coerce' 付きの pd.to_numeric で — 乱れたデータにははるかに安全です。低基数の文字列のために莫大なメモリを節約するのが、「category」の dtype です。小さい値範囲の列のためメモリを 8 倍切り詰められるのが、(int64→int8 の)downcast です。速度と正しさのために、日付のパースには必ず明示的な形式文字列を。

pandas
# Convert a column's dtype
df["age"] = df["age"].astype(int)
df["price"] = df["price"].astype(float)
df["pass"] = df["pass"].astype(bool)
df["city"] = df["city"].astype("category")    # save memory

# Convert with pd.to_numeric (handles bad values)
df["price"] = pd.to_numeric(df["price"], errors="coerce")  # bad -> NaN
df["price"] = pd.to_numeric(df["price"], errors="ignore")  # leave as-is

# Parse dates
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")

# Convert multiple columns at once
df = df.astype({"age": "int8", "score": "float32", "city": "category"})

# Downcast to save memory
df["age"] = pd.to_numeric(df["age"], downcast="integer")

値の置換

分析の前に、センチネル値(-999、'?')を NaN へ交換する主力が、replace です。要素ごとに dict のルックアップを適用するのが、map です(一致しない値が NaN になります)。条件が True の値を保ち残りを置き換えるのが、where で、逆が mask です。新しいオブジェクトを返すのが、これらすべてで、適用するには再代入しましょう。

pandas
# Replace specific values
df["city"].replace({"NYC": "New York", "LA": "Los Angeles"})
df.replace(-999, np.nan)              # whole frame
df.replace(["?", "N/A", ""], np.nan)  # multiple sentinels

# Replace by condition (mask)
df.loc[df["age"] < 0, "age"] = np.nan

# Clip outliers
df["age"] = df["age"].clip(0, 120)

# Map values with a dict (like a lookup)
df["grade"] = df["score"].map({90: "A", 80: "B", 70: "C"})

# Where: keep where condition True, else replace
df["age"].where(df["age"] >= 0, 0)    # set negatives to 0

# Mask: opposite of where
df["age"].mask(df["age"] < 0, 0)
06

データの変換

apply と applymap

要素/行ごとに Python の関数を実行するのが、apply です。柔軟だが遅い(ベクトル化された操作より 100 倍遅い)です。可能な限り、ベクトル化された操作(df['col'] + 1、.str.upper())を必ず推奨しましょう。ベクトル化できないロジック(カスタム文字列のパース、複数列を参照する条件付き変換)に、apply を。行ごとの作業には、axis=1 で、row['col'] 経由で列へアクセスします。

pandas
# Apply a function to each element of a column (Series)
df["age"] = df["age"].apply(lambda x: x + 1)
df["name"] = df["name"].apply(str.upper)

# Apply with multiple args
df["score"] = df["score"].apply(lambda x, n: round(x, n), n=2)

# Apply a function to each ROW (axis=1) — use columns
df["full"] = df.apply(lambda row: f"{row['name']} ({row['age']})", axis=1)

# Apply to every element of a DataFrame (newer: .map)
df = df.map(lambda x: str(x).strip() if isinstance(x, str) else x)

# Vectorized alternative (MUCH faster than apply)
df["age"] = df["age"] + 1  # vectorized, prefer this
df["name"] = df["name"].str.upper()

列の追加と修正

ベクトル化された if-else が、np.where です — lambda 付きの apply よりはるかに速いです。case/when 文のように複数の条件を扱うのが、np.select です。チェーンに優しい列追加の方法が、assign で(パイプラインに最適)、特定の位置に列を置くのが、insert です。列の削除が drop(columns=[...]) であり、del df['col'] よりはるかに明快です。

pandas
# Add a new column
df["full_name"] = df["first"] + " " + df["last"]
df["is_adult"] = df["age"] >= 18

# Conditional column with np.where
df["category"] = np.where(df["age"] >= 18, "adult", "minor")

# Multiple conditions with np.select
conditions = [df["age"] < 18, df["age"] < 65, df["age"] >= 65]
choices = ["minor", "adult", "senior"]
df["group"] = np.select(conditions, choices, default="unknown")

# insert at a specific position
df.insert(2, "score_pct", df["score"] / 100)  # at col index 2

# Assign multiple columns at once (returns new df)
df = df.assign(
    age_months=df["age"] * 12,
    score_squared=df["score"] ** 2,
)

# Drop columns
df.drop(columns=["temp", "junk"])

ビニングと離散化

範囲を等幅のビンへ分割するのが、cut です(空のビンを作り得ます)。等頻度のビンへ分割するのが、qcut です(各ビンが約同じ数)— 歪んだデータには通常より有用です。((0,18] の右端を含むのではなく)[0,18) の左端を含むビンにするのが、right=False です。categorical の dtype になるのが、ビン化された列で、groupby の集約に完璧です。

pandas
# Equal-width bins
df["age_bin"] = pd.cut(df["age"], bins=4)

# Custom bins with labels
df["age_group"] = pd.cut(
    df["age"],
    bins=[0, 18, 30, 50, 100],
    labels=["child", "young", "adult", "senior"],
    right=False,  # left-inclusive: [0, 18)
)

# Equal-frequency bins (quantiles)
df["income_quartile"] = pd.qcut(df["income"], q=4, labels=["Q1","Q2","Q3","Q4"])

# Get bin edges
df["age_bin"].value_counts(sort=False)
pd.cut(df["age"], bins=4).cat.categories  # see the bin ranges

文字列操作(.str アクセサ)

Python の文字列メソッドをベクトル化するのが、.str アクセサです — apply(str.upper) でループしてはいけません。1 つの列を複数へ変えるのが、expand=True 付きの split です(名前の分割に最適)。構造化データをテキストから引き出すのが、名前付きグループ付きの extract です。NaN の入力に対し NaN を返し、その挙動を制御する na= を受け付けるのが、すべての .str メソッドです。

pandas
# All vectorized string methods via .str
df["name"] = df["name"].str.upper()
df["name"] = df["name"].str.lower()
df["name"] = df["name"].str.strip()           # remove leading/trailing
df["name"] = df["name"].str.replace(" ", "_")
df["name"] = df["name"].str.title()           # Title Case

# Split
df["name"].str.split(" ")                     # list per row
df[["first", "last"]] = df["name"].str.split(" ", expand=True)

# Contains / startswith / match (returns boolean)
df["name"].str.contains("li", case=False, na=False)
df["name"].str.startswith("A")
df["name"].str.match(r"^A\w+$")              # regex match

# Extract with regex groups
df["name"].str.extract(r"(?P<first>\w+)\s+(?P<last>\w+)")

# Length
df["name"].str.len()

日付と時刻(.dt アクセサ)

日付の列は必ず先に pd.to_datetime で変換し、その後、コンポーネントへのアクセスには .dt を使いましょう。year/month/day/weekday/hour とタイムゾーンの操作の扉を開くのが、.dt アクセサです。日付を文字列('2024-01-01')と直接比較でき、そののが pandas です。タイムゾーンを意識した datetime の作業には、tz_localize(tz を加える)と tz_convert(tz を変える)があり — naive と aware の datetime を混ぜないこと。

pandas
df["date"] = pd.to_datetime(df["date"])

# Extract parts
df["year"]      = df["date"].dt.year
df["month"]     = df["date"].dt.month
df["day"]       = df["date"].dt.day
df["weekday"]   = df["date"].dt.day_name()    # 'Monday'
df["hour"]      = df["date"].dt.hour
df["is_weekend"] = df["date"].dt.dayofweek >= 5

# Date arithmetic
df["age_days"] = (pd.Timestamp("today") - df["date"]).dt.days

# Format back to string
df["date_str"] = df["date"].dt.strftime("%Y-%m-%d")

# Timezone handling
df["date_utc"] = df["date"].dt.tz_localize("UTC")
df["date_local"] = df["date_utc"].dt.tz_convert("US/Eastern")

# Filter by date
df[df["date"] > "2024-01-01"]
df[df["date"].between("2024-01-01", "2024-12-31")]
07

GroupBy と集約

基本の GroupBy

split-apply-combine に従うのが、groupby です:グループキーで行を分割し、グループごとに関数を適用し、結果を組み合わせます。city でインデックスされた Series を返すのが、groupby('city')['age'].mean() であり、DataFrame を返すのが、リスト付きの agg です。グループごとにすべての行を数えるのが(NaN キーを含め)、size() で、NaN を除外し頻度でソートするのが、value_counts() です。階層的なインデックスを作るのが、複数のグループキーです。

pandas
# Split-Apply-Combine: group rows, compute per group
df.groupby("city")["age"].mean()         # one column, one agg
df.groupby("city")["age"].agg(["mean", "median", "std"])

# Multiple columns
df.groupby("city")[["age", "score"]].mean()

# Group by multiple columns (hierarchical)
df.groupby(["city", "pass"])["age"].mean()

# Quick counts per group
df.groupby("city").size()                # includes NaN groups
df["city"].value_counts()                # excludes NaN, sorted

# Iterate over groups
for name, group in df.groupby("city"):
    print(name, len(group))

複数の集約

最もきれいな方法が、名前付き集約(pandas 0.25+)です — MultiIndex の代わりに、あなたが指定する名前を出力の列が受け取ります。構文が、new_col=('source_col', 'function') です。lambda 経由のカスタム関数は機能しますが、組み込み(mean、sum などが C 最適化です)より遅いです。グループキーを通常の列として欲しいなら、必ず reset_index() を。

pandas
# Different aggregations per column
df.groupby("city").agg({
    "age":   ["mean", "median", "std"],
    "score": ["min", "max", "count"],
})

# Named aggregations (cleaner output, no MultiIndex)
result = df.groupby("city").agg(
    avg_age=("age", "mean"),
    median_age=("age", "median"),
    n_people=("age", "count"),
    max_score=("score", "max"),
)

# Custom aggregation function
df.groupby("city").agg(
    age_range=("age", lambda x: x.max() - x.min()),
)

# Reset index to get a flat DataFrame
result = result.reset_index()

transform と filter

魔法のようなのが、transform です — 入力と同じ長さの Series を返し、各グループの結果をメンバーへ broadcast します。元の行と並んだグループレベルの統計(カテゴリごとの平均)の追加や、グループ平均による欠損値の充填に完璧です。グループごとの真偽条件に基づき、グループ全体を保つか落とすのが、filter です(サンプルが少なすぎる都市の破棄など)。

pandas
# transform: broadcast group result back to original shape
df["age_mean_city"] = df.groupby("city")["age"].transform("mean")
df["age_dev"] = df["age"] - df.groupby("city")["age"].transform("mean")

# Fill missing with group mean
df["score"] = df.groupby("city")["score"].transform(
    lambda s: s.fillna(s.mean()))

# filter: keep/drop entire groups based on a condition
# keep groups with more than 2 rows
big_groups = df.groupby("city").filter(lambda g: len(g) > 2)
# keep groups where average score > 80
df.groupby("city").filter(lambda g: g["score"].mean() > 80)

グループ上の apply

最も柔軟だが(グループごとに任意の関数を実行)、最も遅いのが、groupby 上の apply です。可能な限り、組み込みの集約(mean、sum)か transform を推奨しましょう。Series のインデックスを列とする DataFrame が、関数から Series を返すことで作られます。最大値のインデックスを返すのが、idxmax です — 同じ行の他の列のルックアップに使いましょう。

pandas
# Apply any function per group (most flexible)
def top_scorer(g):
    return g.nlargest(1, "score")

df.groupby("city").apply(top_scorer)
df.groupby("city").apply(lambda g: g.nlargest(2, "score"))

# Normalize within group
df.groupby("city").apply(
    lambda g: (g["score"] - g["score"].mean()) / g["score"].std()
)

# Multiple results per group
def summarize(g):
    return pd.Series({
        "count": len(g),
        "avg_score": g["score"].mean(),
        "top_name": g.loc[g["score"].idxmax(), "name"],
    })

df.groupby("city").apply(summarize)

# include_groups=False (newer pandas) to exclude group cols from g

ピボットテーブルと Crosstab

groupby + unstack を組み合わせたのが、pivot_table です — 長いデータをマトリックスへ変えるのに完璧です(都市 × 合格ごとの平均スコアなど)。行/列の合計を加えるのが、margins=True です。組み合わせのカウント(頻度表)のための特殊化されたピボットが、crosstab で、行の比率を与えるのが、normalize='index' です。逆の、幅から長い形式へ戻すのが、melt です。

pandas
# pivot_table: groupby + reshape in one step
pd.pivot_table(df, values="score", index="city", columns="pass",
               aggfunc="mean")
pd.pivot_table(df, values="score", index="city", columns="pass",
               aggfunc=["mean", "count"], margins=True)

# Multiple values
pd.pivot_table(df, values=["age", "score"], index="city",
               aggfunc={"age": "mean", "score": "max"})

# crosstab: frequency table of two (or more) categoricals
pd.crosstab(df["city"], df["pass"])
pd.crosstab(df["city"], df["pass"], normalize="index")  # row %
pd.crosstab(df["city"], df["pass"], values=df["score"],
            aggfunc="mean")  # like a pivot

# Melt a pivot back to long
wide = pd.pivot_table(df, values="score", index="city", columns="pass")
long = wide.reset_index().melt(id_vars="city", var_name="pass",
                                value_name="score")
08

マージと結合

merge(SQL 風の join)

pandas の SQL JOIN が、merge です。inner/left/right/outer/cross を選ぶのが、how です。on は必ず明示的に指定し、キーに異なる名前があるなら left_on/right_on を使いましょう。重なる列の曖昧さを解消するのが、suffixes です(デフォルトの _x/_y は不透明です)。結合のカーディナリティが間違っていれば例外を出すのが、validate='m:1'(か '1:1'、'1:m'、'm:m')で — うっかりの行複製への素晴らしい安全装置です。

pandas
# Like SQL JOIN
pd.merge(df1, df2, on="id")                     # inner join (default)
pd.merge(df1, df2, on="id", how="left")         # left join
pd.merge(df1, df2, on="id", how="right")
pd.merge(df1, df2, on="id", how="outer")        # full outer
pd.merge(df1, df2, on="id", how="cross")        # cartesian product

# Different column names in each frame
pd.merge(df1, df2, left_on="user_id", right_on="id")

# Join on index
pd.merge(df1, df2, left_index=True, right_index=True)

# Suffixes for overlapping non-key columns
pd.merge(df1, df2, on="id", suffixes=("_left", "_right"))

# Validate to catch unexpected duplicates
pd.merge(df1, df2, on="id", validate="m:1")  # many-to-one expected

concat(スタッキング)

DataFrame を縦に(axis=0、デフォルト)か横に(axis=1)スタックするのが、concat です。元のインデックスを破棄し、きれいな 0..n-1 を作るのが、ignore_index=True です — スタッキング時には通常これが欲しいものです。共有された列だけを保つのが、join='inner' です(フレームがずれたとき有用)。重複したインデックスでエラーを出すのが、verify_integrity=True です。乱れた追加への安全網です。

pandas
# Stack vertically (rows) — same columns
pd.concat([df1, df2])
pd.concat([df1, df2], ignore_index=True)   # reindex 0..n-1

# Stack horizontally (columns)
pd.concat([df1, df2], axis=1)

# Concat with keys (hierarchical index)
pd.concat([df1, df2], keys=["q1", "q2"])

# Append (deprecated; use concat)
# df1.append(df2)  # deprecated, use pd.concat

# Verify columns match when stacking
pd.concat([df1, df2], verify_integrity=True)  # error on dup index

# Join options for mismatched columns
pd.concat([df1, df2], join="inner")  # keep only shared columns
pd.concat([df1, df2], join="outer")  # keep all, NaN for missing

join(インデックスベース)

インデックス上の結合のよくあるケースのための merge の糖衣構文が、join です。両方のフレームが既に意味のあるインデックスを持つとき、わずかに簡潔です。列上の結合には、merge の方が明快です。一度に複数の DataFrame を join できるのが(リストを渡す)、join であり — いくつかのルックアップテーブルをメインのフレームへ組み合わせるのに便利です。

pandas
# join is merge optimized for joining on the index
df1.join(df2)                          # join on index
df1.join(df2, how="left")              # left, right, inner, outer
df1.join([df2, df3])                   # join multiple at once

# join on a column (set index first)
df1.set_index("id").join(df2.set_index("id"), how="inner")

# Suffix for overlapping columns
df1.join(df2, lsuffix="_left", rsuffix="_right")

# When to use join vs merge:
# - join: keys are the index (faster, cleaner)
# - merge: keys are regular columns (more flexible)

combine と update

別の DataFrame から欠損値を充填する慣用的な方法が、combine_first です — SQL の coalesce のように。その場で df1 を修正するのが、update です。df2 が非 NaN の値を持つ所でのみ上書きします。より新しい部分的なデータでマスター dataset をパッチするのに、これらが素晴らしいです。素早い union/dedup が、concat + drop_duplicates ですが、本物の集合の操作には、indicator=True 付きの merge を検討しましょう。

pandas
# combine_first: fill NaN in df1 with values from df2
df1.combine_first(df2)
# Where df1 is NaN, take df2's value; otherwise keep df1.

# update: overwrite df1 in place with non-NaN from df2
df1.update(df2)

# combine with a custom function
import numpy as np
df1.combine(df2, lambda s1, s2: np.minimum(s1, s2))

# Concat then drop duplicates (union with dedup)
pd.concat([df1, df2]).drop_duplicates()

マージ結果の確認

join のデバッグには非常に有用なのが、indicator=True です — どの行がどちらの側から来たか伝えます。マージ後の行数の急な跳ね上がりの通常の意味は、片方のフレームの重複キーです。結合の前に、キー上の value_counts() で確認しましょう。「df1 を、キーが df2 に存在する行へフィルタする」ためには、isin(セミ結合)を使い — 本物のマージは不要です。

pandas
# indicator=True adds a '_merge' column showing the source
merged = pd.merge(df1, df2, on="id", how="outer", indicator=True)
# _merge values: 'left_only', 'right_only', 'both'

# Find rows in df1 but not df2 (anti-join)
only_left = merged[merged["_merge"] == "left_only"]

# Find rows in both (intersection)
both = merged[merged["_merge"] == "both"]

# Detect unexpected row explosion (duplicate keys)
print(len(df1), len(df2), len(merged))
# if len(merged) >> max(len(df1), len(df2)) you have duplicate keys

# isin for a simple semi-join (filter df1 to keys in df2)
df1[df1["id"].isin(df2["id"])]            # semi-join
df1[~df1["id"].isin(df2["id"])]           # anti-join
09

データのリシェイプ

melt(幅から長へ)

幅の形式のデータ(エンティティごとに 1 行、多くの測定列)を長い形式(測定ごとに 1 行)へ変えるのが、melt です。これは、ほとんどの ML/統計ライブラリが好む、tidy な形式です。そのまま保たれる識別列が、id_vars で、残りすべてが var/value のペアになります。groupby、フィルタ、プロットがしやすいのが、長い形式です。

pandas
# melt: unpivot columns into rows
df_wide = pd.DataFrame({
    "id": [1, 2],
    "q1": [10, 20],
    "q2": [15, 25],
    "q3": [20, 30],
})

long = df_wide.melt(id_vars="id", var_name="quarter", value_name="score")
#    id quarter  score
# 0   1      q1     10
# 1   2      q1     20
# ...

# Melt only specific columns
df_wide.melt(id_vars="id", value_vars=["q1", "q2"])

# Keep the wide columns too (with identifier)
df_wide.melt(id_vars="id", value_vars=["q1","q2","q3"],
             var_name="quarter", value_name="score",
             ignore_index=True)

pivot(長から幅へ)

集約なしで長いものを幅へリシェイプするのが、pivot です — 重複する(index、columns)のペアがあれば失敗するため、その場合は aggfunc 付きの pivot_table を使いましょう。混乱し得るのが、ピボットの列になるのが、列名であることです。結果を片付けるのが、reset_index() と columns.name=None です。melt の逆が、pivot です。

pandas
# pivot: long to wide (without aggregation)
df_long = pd.DataFrame({
    "id": [1, 1, 1, 2, 2, 2],
    "quarter": ["q1", "q2", "q3", "q1", "q2", "q3"],
    "score": [10, 15, 20, 30, 35, 40],
})

wide = df_long.pivot(index="id", columns="quarter", values="score")
# quarter  q1  q2  q3
# id
# 1        10  15  20
# 2        30  35  40

# pivot fails on duplicate index/value combos — use pivot_table then
df_long.pivot_table(index="id", columns="quarter",
                    values="score", aggfunc="sum")

# Restore a regular column from the index
wide = wide.reset_index()
wide.columns.name = None

stack と unstack

MultiIndex のオブジェクト上で、行と列の間でレベルを動かすのが、stack/unstack です — グループ化された結果のリシェイプに強力です。MultiIndex を持つ Series を作るのが、複数キーでの groupby であり、1 つのレベルをマトリックスビューの列へ変えるのが、unstack です。逆が、stack です。下でピボットテーブルを支える積み木が、これらです。

pandas
# MultiIndex column example
df = pd.DataFrame({
    ("A", "x"): [1, 2],
    ("A", "y"): [3, 4],
    ("B", "x"): [5, 6],
})

# stack: turn column level into inner row index
stacked = df.stack()
# Now a Series with MultiIndex (row, col_level_2)

# unstack: inverse — turn row level into column level
stacked.unstack()

# Common use: reshape grouped result
g = df.groupby(["city", "year"])["score"].mean()
# city  year
# NYC   2023    80
# NYC   2024    85
# LA    2023    70

g.unstack("year")  # years become columns
#        2023  2024
# city
# NYC    80    85
# LA     70    NaN

リストの爆発

リストの列を、リスト要素ごとに 1 行へ変え、他の列を複製するのが、explode です — ネストしたデータ(JSON 配列、マルチタグのレコード)には不可欠です。分析の前に、リスト値の列を正規化するきれいな方法です。逆方向へ(行をリストへ組み合わせる)行くには、groupby + apply(list) を。

pandas
# explode: turn list-like values into separate rows
df = pd.DataFrame({
    "id": [1, 2],
    "tags": [["python", "ml"], ["sql", "db", "etl"]],
})
#              id           tags
# 0             1  [python, ml]
# 1             2  [sql, db, etl]

exploded = df.explode("tags")
#    id    tags
# 0   1  python
# 0   1      ml
# 1   2     sql
# 1   2      db
# 1   2    etl

# Useful after str.split
df["tags"] = df["tags_str"].str.split(",")
exploded = df.explode("tags")

# Aggregate back: groupby + list
exploded.groupby("id")["tags"].apply(list)

MultiIndex の操作

2D で高次元のデータを表現できるのが、MultiIndex(階層的インデックス)です。すべての外側のレベルを指定する必要なく、特定のレベルで選択するのが、xs(クロスセクション)です。異なるビューのためにレベルを並べ替えるのが、swaplevel と sort_index(level=) です。ほとんどの時間、作業しやすい通常の列へ、MultiIndex を平坦化するのが、reset_index() です。

pandas
# Create a MultiIndex DataFrame
idx = pd.MultiIndex.from_tuples([("NYC", 2023), ("NYC", 2024),
                                  ("LA", 2023)], names=["city", "year"])
df = pd.DataFrame({"score": [80, 85, 70]}, index=idx)

# Select by outer level
df.loc["NYC"]              # all NYC rows
df.xs("NYC", level="city") # same, more explicit

# Select by inner level
df.xs(2023, level="year")

# Swap levels
df.swaplevel()

# Sort by level
df.sort_index(level="year")

# Reset one level back to a column
df.reset_index(level="year")

# Flatten columns after a groupby
g = df.groupby(["city", "year"]).mean().reset_index()
10

ソートとランキング

値のソート

辞書式にソートするのが、列のリストと一致する ascending のリスト付きの sort_values です — 最初に主キー、その後にタイブレーカーです。NaN がどこへ行くかの制御が、na_position です(デフォルト「last」)。安定であり、そのため等しいキーが元の順序を保ちます。インデックスの順序を変えるのが、ソートで、その後のきれいな連続インデックスを与えるのが、reset_index(drop=True) です。

pandas
# Sort by one column
df.sort_values("age")
df.sort_values("age", ascending=False)

# Sort by multiple columns (stable sort)
df.sort_values(["city", "age"], ascending=[True, False])
# city ascending, age descending within each city

# Put NaNs first or last
df.sort_values("score", na_position="first")

# In-place (modifies df)
df.sort_values("age", inplace=True)

# Sort by index
df.sort_index()
df.sort_index(axis=1)            # sort columns by name
df.sort_index(ascending=False)

# Reset index after sorting
df.sort_values("age").reset_index(drop=True)

ランキング

パーセンタイル、グループ内のトップ N、ノンパラメトリック統計の計算には、rank が不可欠です。ギャップのない 1,2,2,3 を与えるのが、method='dense' です — メダルや成績に最適。出現順で同点を破るのが、「first」です。パーセンタイルを返すのが、rank(pct=True) です。グループ内のランキングを計算するのが(地域ごとのトップの販売者など)、groupby + rank です。

pandas
# Default rank: average for ties (1, 2.5, 2.5, 4)
df["rank"] = df["score"].rank()

# Methods for handling ties
df["score"].rank(method="average")  # default
df["score"].rank(method="min")      # ties get the min rank
df["score"].rank(method="max")      # ties get the max rank
df["score"].rank(method="first")    # ties broken by order of appearance
df["score"].rank(method="dense")    # 1, 2, 2, 3 (no gaps)

# Ascending / descending
df["score"].rank(ascending=False)   # highest = rank 1

# Rank as percentile
df["pct"] = df["score"].rank(pct=True)

# Rank within groups
df["city_rank"] = df.groupby("city")["score"].rank(ascending=False)

nlargest と nsmallest

最適化されているのが、nlargest/nsmallest です。内部でヒープを使うため、数行だけが必要なとき(100 万からのトップ 10 など)、フレーム全体のソートより速いです。「グループごとのトップ N」の慣用句が、groupby + apply(nlargest) ですが、一部のデータでは、フルのソート + groupby の head より遅いです。タイブレーキングを制御するのが、keep です('first'、'last'、'all')。

pandas
# Top N rows — faster than sort_values + head on large data
df.nlargest(5, "score")            # top 5 by score
df.nlargest(5, "score", keep="first")  # tie-breaking
df.nsmallest(3, "age")             # youngest 3

# Top N per group
df.groupby("city").apply(lambda g: g.nlargest(2, "score"))

# Bottom N with multiple columns
df.nsmallest(5, ["age", "score"])

# Equivalent sort_values (slower for big data)
df.sort_values("score", ascending=False).head(5)

インデックスと列のソート

列をアルファベット順にするのが、sort_index(axis=1) です — マージが任意の順で新しい列を加えた後に手軽です。キーの列(「id」、「name」など)を最初に置くには、リストの連結を使いましょう:前の列と、その後の残りです。再順序付けと列の部分集合の、最も明快な方法が、明示的な列の選択 df[[...]] です。

pandas
# Sort the row index
df.sort_index()
df.sort_index(ascending=False)

# Sort columns alphabetically
df.sort_index(axis=1)
df.sort_index(axis=1, ascending=False)

# Reorder columns explicitly
df[["name", "age", "city", "score"]]

# Reorder to a pattern
cols = sorted(df.columns)
df = df[cols]

# Move specific columns to the front
front = ["id", "name"]
df = df[front + [c for c in df.columns if c not in front]]

キーによるソート

ソート前に列へ関数を適用するのが、sort_values(key=) です — 大文字小文字を区別しないソートか、長さベースのソートです。定義されたカテゴリの順でソートされるのが、(アルファベット順でない)順序付き Categorical の列です — 曜日、サイズ(S<M<L)、カスタムのビジネスの順序に最適です。(file1、file2、file10 の)自然ソートには、数字を分割するカスタムキーが要ります。

pandas
# Sort by a function of the values (key, like sorted())
df.sort_values("name", key=lambda s: s.str.lower())
# case-insensitive sort

# Sort by string length
df.sort_values("name", key=lambda s: s.str.len())

# Sort by a custom order (categorical)
df["city"] = pd.Categorical(df["city"],
    categories=["NYC", "LA", "SF"], ordered=True)
df.sort_values("city")  # follows the defined category order

# Natural sort (numbers in strings)
import re
def natural_key(s):
    return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)]
df.sort_values("version", key=lambda s: s.map(natural_key))
11

Datetime の操作

日付のパース

分かっているなら、必ず明示的な形式文字列を渡しましょう — 推論より 10 倍速く曖昧さを避けます(01/02/2024 が 1 月 2 日か 2 月 1 日か)。パースできない値を NaT(Not a Time、datetime の NaN)へ変えるのが、errors='coerce' です。year/month/day の列を持つ DataFrame 上の pd.to_datetime が、パートから日付を組み立てます。

pandas
# Parse strings to datetime
df["date"] = pd.to_datetime(df["date"])
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")  # faster + safer

# Handle mixed formats
df["date"] = pd.to_datetime(df["date"], format="mixed")

# Coerce bad values to NaT (datetime NaN)
df["date"] = pd.to_datetime(df["date"], errors="coerce")

# Parse on read
df = pd.read_csv("data.csv", parse_dates=["date", "created_at"])

# Parse multiple columns into one
df["datetime"] = pd.to_datetime(df[["year", "month", "day"]])

# Timestamp (scalar)
pd.Timestamp("2024-06-15 14:30:00")
pd.Timestamp.now()
pd.Timestamp("2024-06-15").tz_localize("UTC")

date_range と Periods

柔軟な freq 文字列付きで DatetimeIndex のシーケンスを生成するのが、date_range です:'D'(日)、'H'(時)、'MS'(月開始)、'W-MON'(毎週月曜)、'Q'(四半期)です。週末をスキップするのが、bdate_range です。瞬間ではなく区間(丸 1 か月、丸 1 四半期)を表すのが、Period です — レポートの期間に有用です。強力なのが、freq の別名です:'2D' = 2 日ごと。

pandas
# Generate a sequence of dates
pd.date_range("2024-01-01", "2024-01-10")           # daily
pd.date_range("2024-01-01", periods=10)             # 10 days
pd.date_range("2024-01-01", periods=10, freq="H")   # hourly
pd.date_range("2024-01-01", "2024-12-31", freq="MS") # month start
pd.date_range("2024-01-01", "2024-12-31", freq="W-MON") # weekly Mondays

# Business days only
pd.bdate_range("2024-01-01", periods=10)

# Period (represents an interval, like a month)
p = pd.Period("2024-06", freq="M")
p.to_timestamp()    # convert to the month's start
p.start_time, p.end_time

# Period range
pd.period_range("2024-01", "2024-12", freq="M")

リサンプリングと頻度変換

時系列のための groupby が、resample です — 集約によるダウンサンプリング(W/M/Q の sum と mean)、充填によるアップサンプリング(ffill、interpolate)です。DatetimeIndex を要求するのが、resample です。ビンの境界が左か右の期間に属するかを制御するのが、「label」と「closed」の引数で — off-by-one のエラーを避けるため、週次/月次の集約には重要です。

pandas
ts = pd.Series(range(100), index=pd.date_range("2024-01-01", periods=100, freq="D"))

# Downsample (more frequent -> less frequent): use agg
ts.resample("W").sum()       # weekly sum
ts.resample("M").mean()      # monthly mean
ts.resample("QE").max()      # quarterly max

# Upsample (less -> more frequent): need fill
ts.resample("H").asfreq()            # hourly, NaN for gaps
ts.resample("H").ffill()             # forward fill
ts.resample("H").interpolate()       # linear interp

# Custom aggregation
ts.resample("W").agg(["mean", "std", "count"])

# Resample with multiple columns
df.resample("M").agg({"sales": "sum", "visits": "mean"})

# Use 'label' and 'closed' to control bin edges
ts.resample("M", label="right", closed="right").sum()

シフトとラグ

時系列の特徴エンジニアリングの基礎が、shift、diff、pct_change です。ラグを作るのが、shift(1) です(今日の行へ整列された昨日の値)— 自己回帰の特徴に完璧です。未来を覗くのが、shift(-1) です(次ステップのターゲット構築に使いましょう)。変化を測るのが、diff と pct_change です。これらの使用前には必ず時間でソートし、境界での NaN に注意しましょう。

pandas
# Shift values forward/backward (for time-series features)
ts.shift(1)          # move values down by 1 (yesterday's value)
ts.shift(-1)         # move up by 1 (tomorrow's value)

# Difference (today - yesterday)
ts.diff()            # first difference
ts.diff(7)           # week-over-week difference

# Percentage change
ts.pct_change()
ts.pct_change(periods=7)  # 7-day pct change

# Lag features for ML
df["lag_1"]  = df["sales"].shift(1)
df["lag_7"]  = df["sales"].shift(7)
df["roll_7"] = df["sales"].rolling(7).mean()
df["target_next"] = df["sales"].shift(-1)  # next-day target

# Shift by a time frequency
ts.shift(1, freq="D")   # shift the INDEX by 1 day

Rolling と Expanding の窓

スライディングウィンドウにわたる統計の計算が、rolling です — 移動平均、ボラティリティなど。部分的なウィンドウが計算できるのが、min_periods です(さもなければ、最初の N-1 が NaN です)。指数加重の移動平均を与えるのが、ewm です(最近の点がより重み付けされる — 財務で一般的です)。開始から成長するのが、expanding です(累積統計)。行数の窓と違い、不規則なサンプリングを正しく扱うのが、時間ベースの窓('7D')です。

pandas
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=float)

# Rolling window (fixed-size sliding window)
s.rolling(3).mean()        # 3-period moving average
s.rolling(7).std()
s.rolling(3, min_periods=1).mean()  # allow partial windows

# Custom aggregation
s.rolling(3).apply(lambda x: x.max() - x.min())

# Exponentially weighted (decaying weights)
s.ewm(span=7).mean()       # EWMA — recent data weighted more
s.ewm(alpha=0.3).mean()

# Expanding window (grows from start)
s.expanding().mean()       # cumulative mean
s.expanding().max()        # running max

# Window with time-based offset (needs DatetimeIndex)
ts.rolling("7D").mean()    # 7-day window, not 7 rows
12

カテゴリデータ

カテゴリの作成

ルックアップテーブル付きの整数コードとして文字列を保存するのが、category の dtype です。低基数の列(100 万行を持つ 5 一意値の都市列)のための莫大なメモリ節約です。比較(size > 'M')をサポートし、カテゴリの順で(アルファベット順でなく)ソートするのが、順序付きカテゴリです。既知で小さい値のセットを持つ列には、category を。

pandas
# Convert to category dtype
df["city"] = df["city"].astype("category")

# Create with explicit categories
s = pd.Categorical(["a", "b", "a", "c"],
                    categories=["a", "b", "c", "d"])

# Ordered categorical (for sorting & comparisons)
size = pd.Categorical(["M", "L", "S", "XL"],
                       categories=["S", "M", "L", "XL"],
                       ordered=True)
size > "M"  # works because it's ordered

# Memory savings
df["city"].memory_usage(deep=True)              # object
df["city"].astype("category").memory_usage(deep=True)  # much less

.cat アクセサ

カテゴリのメタデータを操作するのが、.cat アクセサです。実際の値へカテゴリのリストを切り詰めるのが、remove_unused_categories です — フィルタリング後には重要で、多くのカテゴリが空になります。基礎のコードを変えずラベルを変えるのが、rename_categories です。ソート順を変えるのが、reorder_categories です。新しい Series を返すのが、これらすべてで、適用するには再代入しましょう。

pandas
s = pd.Series(["a", "b", "a", "c"], dtype="category")

# Inspect categories
s.cat.categories        # Index(['a', 'b', 'c'])
s.cat.codes             # integer codes
s.value_counts()

# Add / remove categories
s = s.cat.add_categories(["d"])
s = s.cat.remove_categories(["d"])     # values in 'd' become NaN
s = s.cat.remove_unused_categories()

# Rename categories
s = s.cat.rename_categories({"a": "alpha", "b": "beta"})

# Reorder categories
s = s.cat.reorder_categories(["c", "b", "a"])

# Set / unset ordering
s = s.cat.as_ordered()
s = s.cat.as_unordered()

カテゴリの操作

groupby と value_counts のために、object(文字列)の操作より一般に速いのが、カテゴリの操作です。2 つのカテゴリ列をマージするときは、まず set_categories でカテゴリセットを整列させましょう — 一致しないカテゴリが、遅いマージとサイレントな NaN を引き起こします。category のオーバーヘッドが値しないとき(自由テキストの列など)、astype(str) で文字列/object へ戻しましょう。

pandas
# Operations preserve categorical dtype where possible
s = pd.Series(["low", "high", "med", "low"], dtype="category")
s.value_counts()

# Comparison on ordered categoricals
size = pd.Series(["M", "L", "S"], dtype="category")
size = size.cat.as_ordered().cat.reorder_categories(["S","M","L","XL"])
size > "M"   # boolean Series

# Groupby works as expected
df.groupby("city")["score"].mean()

# Converting back
df["city"] = df["city"].astype(str)         # to string
df["city"] = df["city"].astype("object")    # to object

# Beware: merges between categoricals can be slow if categories differ
# Align categories before merging:
cats = sorted(set(df1["city"].cat.categories) |
              set(df2["city"].cat.categories))
df1["city"] = df1["city"].cat.set_categories(cats)
df2["city"] = df2["city"].cat.set_categories(cats)

メモリの最適化

大きなデータをロードするとき、メモリの最適化が効きます:低基数の文字列を category へ(10〜100 倍の節約)、数値を downcast(小さい範囲の整数は int64→int8、float64→float32)しましょう。object よりメモリ効率が良く、object より NaN をよく扱うのが、「string」の dtype(pandas 1.0+)です。経験則:nunique/len < 0.5 なら、category が値します。

pandas
# Check current memory
df.info(memory_usage="deep")

# Convert object columns to category when cardinality is low
for col in df.select_dtypes(include="object"):
    if df[col].nunique() / len(df) < 0.5:  # <50% unique
        df[col] = df[col].astype("category")

# Downcast numeric columns
df["age"] = pd.to_numeric(df["age"], downcast="integer")
df["score"] = pd.to_numeric(df["score"], downcast="float")

# Use string dtype (pandas 1.0+) instead of object
df["name"] = df["name"].astype("string")

# Compare memory before/after
before = df.memory_usage(deep=True).sum()
# ... optimize ...
after = df.memory_usage(deep=True).sum()
print(f"Reduced from {before/1e6:.1f}MB to {after/1e6:.1f}MB")

ダミー変数(One-Hot)

カテゴリ列を 0/1 のインジケータ列へ one-hot エンコードするのが、get_dummies です — カテゴリを扱えない線形モデルの前には不可欠です。(多重共線性の)ダミー変数の罠を避けるのが、線形回帰のための drop_first です。ML パイプラインには、get_dummies より、sklearn の OneHotEncoder を推奨しましょう(handle_unknown='ignore' により、テスト時の未知のカテゴリを扱えます)。

pandas
# One-hot encode categoricals
pd.get_dummies(df["city"])
pd.get_dummies(df, columns=["city", "pass"])  # encode multiple

# Drop first to avoid multicollinearity (for linear models)
pd.get_dummies(df["city"], drop_first=True)

# With a prefix
pd.get_dummies(df["city"], prefix="city")

# From categorical with all categories
pd.get_dummies(df["city"].astype("category"))

# Alternatively, sklearn's OneHotEncoder (for ML pipelines)
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
X_ohe = ohe.fit_transform(df[["city"]])
13

パフォーマンスと最適化

ベクトル化(iterrows の回避)

pandas のパフォーマンスの第 1 の罪が、iterrows です — ベクトル化された操作より 100〜1000 倍遅いです。必ずベクトル化された列の操作(df['a'] + df['b'])、文字列には .str、if-else には np.where を推奨しましょう。本当にループしなければならないなら、iterrows よりはるかに速いのが、itertuples(Series ではなく namedtuple)です。複雑なロジックには、numba や cython を検討するか、.to_numpy() で numpy へ取り出しましょう。

pandas
# BAD: iterrows is extremely slow
for idx, row in df.iterrows():
    df.loc[idx, "x"] = row["a"] + row["b"]

# GOOD: vectorized operations
df["x"] = df["a"] + df["b"]

# GOOD: .str accessor for strings
df["name"] = df["name"].str.upper()

# GOOD: np.where for conditionals
df["cat"] = np.where(df["a"] > 0, "pos", "neg")

# If you must iterate (rare), use itertuples (faster than iterrows)
for row in df.itertuples():
    process(row.a, row.b)

# Or .to_numpy() / .values for raw array loops
for row in df[["a", "b"]].to_numpy():
    ...

# Benchmark
%timeit df["a"] + df["b"]
%timeit df.apply(lambda r: r["a"] + r["b"], axis=1)

eval と query

文字列の式をパースし numexpr で評価するのが、eval と query です。大きな DataFrame 上では、中間配列の作成を避け C レベルの評価を使うため、Python の算術より 2〜4 倍速くなり得ます。小さいデータでは(パースのオーバーヘッド)、利得が縮みます。大きなフレーム上の複雑な式に有用ですが — 常に速いわけではないため、必ずベンチマークしましょう。

pandas
# eval: evaluate string expressions (uses numexpr, faster on big data)
df.eval("total = a + b + c", inplace=True)
df.eval("ratio = a / (b + c)")
df.eval("c = a > b")

# Multiple operations in one eval (efficient)
df.eval("""
total = a + b
ratio = a / b
flag = a > 10
""", inplace=True)

# query: boolean filter via string (same engine)
df.query("a > 0 and b < 10")

# Local variables with @
threshold = 5
df.query("a > @threshold")

# eval is faster than Python arithmetic on large frames
# because it avoids intermediate arrays

効率的な dtype

メモリのための最も簡単な大きな勝ちが、正しい dtype の選択です:整数の downcast(int64→int8 が 8 倍節約)、低基数の文字列には category(10〜100 倍)、object の代わりに「string」です。NaN のある整数列を扱うのが、nullable な Int64(大文字の I)です — 通常の int64 が NaN を保持できないため、そのような列が float64 をデフォルトとします。ほとんどゼロのデータに役立つのが、sparse の dtype です。

pandas
# Downcast numerics
df["age"] = pd.to_numeric(df["age"], downcast="unsigned")  # 0-255
df["score"] = pd.to_numeric(df["score"], downcast="float")

# Use category for low-cardinality strings
df["city"] = df["city"].astype("category")

# Use 'string' dtype instead of object
df["name"] = df["name"].astype("string")

# Use Nullable integers (Int64 with capital I) for ints with NaN
df["count"] = df["count"].astype("Int64")  # supports NaN

# Sparse for mostly-zero data
s = pd.Series([0, 0, 0, 1, 0, 0]).astype("Sparse[int]")

# Compare memory
df["city"].astype("object").memory_usage(deep=True)
df["city"].astype("category").memory_usage(deep=True)

チャンク化された処理

イテレータを返すのが、read_csv(chunksize=...) です。各チャンクがその行数の DataFrame であるため、メモリより大きいファイルを処理できます。チャンクごとに集約し、その後部分的な結果を組み合わせましょう。サーバー側のカーソルを使うのが、SQL の chunksize です。Spark なしでギガバイト規模のデータを扱う最も簡単な方法が、これです。本物のビッグデータには、Dask か Polars を検討しましょう。

pandas
# Process a large CSV in chunks (low memory)
chunk_iter = pd.read_csv("huge.csv", chunksize=100_000)

results = []
for chunk in chunk_iter:
    # process each chunk (filter, aggregate, etc.)
    result = chunk.groupby("city")["sales"].sum()
    results.append(result)

# Combine chunk results
total = pd.concat(results).groupby(level=0).sum()

# Or use the iterator directly
for i, chunk in enumerate(pd.read_csv("huge.csv", chunksize=50000)):
    chunk.to_parquet(f"part_{i:04d}.parquet")

# For SQL, use server-side cursors
chunks = pd.read_sql("SELECT * FROM big_table", engine,
                     chunksize=100000)

プロファイリングとベンチマーク

最適化の前に必ずベンチマークしましょう — アプローチを素早く比較するのが、%timeit です。完全な HTML のレポート(統計、相関、欠損)を生成するのが、ydata-profiling(旧 pandas-profiling)で — EDA には非常に有用です。見るべきもの:SettingWithCopyWarning です。代入が永続しないかもしれないことを合図し、サイレントなバグのよくある源です。開発中にこれらのバグをエラーとして捉えるには、mode.chained_assignment='raise' を設定しましょう。

pandas
# Time an operation
%timeit df["a"] + df["b"]

# Line profiling (install line_profiler)
# %load_ext line_profiler
# %lprun -f my_function my_function(df)

# Memory profiling (install memory_profiler)
# %load_ext memory_profiler
# %memit df.groupby("city").sum()

# pandas profiling report (install ydata-profiling)
# from ydata_profiling import ProfileReport
# ProfileReport(df).to_file("report.html")

# Quick stats
df.info(memory_usage="deep")
df.describe(include="all")

# Find slow ops
import pandas as pd
pd.set_option("mode.chained_assignment", "warn")  # catch copy bugs
14

データベースと SQL

SQL からの読み取り

接続プーリングと方言の違いを扱うのが、SQLAlchemy のエンジンです — 生の DBAPI の接続の代わりに、これらを使いましょう。SQL インジェクションを防ぐため、ユーザー提供の値には必ずパラメータ化されたクエリ(params=)を使いましょう。バッチで大きなテーブルをストリーミングするのが、chunksize です。複雑なクエリは SQL で書き(データベースが最適化します)、結果の処理を pandas に任せましょう。

pandas
from sqlalchemy import create_engine
import pandas as pd

# Create an engine (connection pool)
engine = create_engine("sqlite:///my.db")
engine = create_engine("postgresql://user:pass@host:5432/db")
engine = create_engine("mysql+pymysql://user:pass@host/db")

# Read a whole table
df = pd.read_sql("users", engine)

# Read a query
df = pd.read_sql("SELECT * FROM users WHERE age > 18", engine)

# Parameterized queries (safe from SQL injection)
df = pd.read_sql(
    "SELECT * FROM users WHERE city = %s",
    engine,
    params=("NYC",),
)

# Chunked reads for large tables
for chunk in pd.read_sql("SELECT * FROM big", engine, chunksize=100000):
    process(chunk)

SQL への書き込み

テーブルを落とし再作成するのが、if_exists='replace' で、行を加えるのが「append」、テーブルが存在すれば例外を出すのが「fail」(デフォルト)です。行を 1 つの INSERT 文へバッチするのが、method='multi' で — 1 行 1 ステートメントのデフォルトよりはるかに速いです。メモリとラウンドトリップのバランスを取るのが、非常に大きな書き込みのための chunksize=10000 です。インデックスが本物のデータでない限り、必ず index=False を渡しましょう。

pandas
# Write a DataFrame to a SQL table
df.to_sql("users", engine, if_exists="replace", index=False)
df.to_sql("users", engine, if_exists="append", index=False)  # add rows

# Specify schema and dtype
from sqlalchemy.types import VARCHAR, INTEGER
df.to_sql("users", engine, if_exists="replace",
          dtype={"name": VARCHAR(100), "age": INTEGER()})

# Write in chunks (for large DataFrames)
df.to_sql("users", engine, if_exists="append",
          chunksize=10000, method="multi")

# method='multi' uses a single INSERT with multiple rows (faster)
# For PostgreSQL, method='multi' with chunksize ~10000 is optimal

# Don't write the index unless it's meaningful data
# index=False avoids a spurious 'index' column

pandas での SQL 風の操作

pandas へマッピングされるのが、ほとんどの SQL の操作です:列の選択が SELECT、真偽インデックスが WHERE、groupby が GROUP BY、merge が JOIN、concat+drop_duplicates が UNION、np.where が CASE WHEN です。これらのマッピングを知れば、正しい道具を選べます:サーバー上の複雑な結合/集約には SQL(DB に最適化させます)、反復的な分析とプロットには pandas を。

pandas
# SELECT cols
df[["name", "age"]]
# WHERE
df[df["age"] > 18]
# GROUP BY + aggregations
df.groupby("city")["age"].mean()
# ORDER BY
df.sort_values("age", ascending=False)
# LIMIT
df.head(10)
# DISTINCT
df["city"].unique()
df.drop_duplicates(subset=["city"])
# JOIN
pd.merge(df1, df2, on="id", how="inner")
# UNION
pd.concat([df1, df2]).drop_duplicates()
# CASE WHEN
np.where(df["age"] >= 18, "adult", "minor")
# HAVING
g = df.groupby("city").filter(lambda g: g["age"].mean() > 30)

text() での SQL 実行

生の SQL 文字列のために text() を要求するのが、SQLAlchemy 2.0 です — 信頼された SQL を、信頼できないパラメータから分離するセキュリティの手段です。成功時に自動コミットし例外時にロールバックするトランザクションを開くのが、engine.begin() です — 書き込みには必ずこれを使いましょう。インジェクションを防ぐためには、:name と params の dict でパラメータを束縛しましょう。

pandas
from sqlalchemy import text

# Use text() for explicit SQL (recommended over raw strings)
query = text("SELECT city, COUNT(*) as n FROM users GROUP BY city")
df = pd.read_sql(query, engine)

# Bind parameters safely
query = text("SELECT * FROM users WHERE age > :min_age AND city = :city")
df = pd.read_sql(query, engine,
                 params={"min_age": 18, "city": "NYC"})

# Execute DDL or DML (non-SELECT)
with engine.begin() as conn:  # transaction
    conn.execute(text("CREATE INDEX idx_city ON users(city)"))
    conn.execute(text("DELETE FROM users WHERE id = :id"),
                 {"id": 999})

Parquet 対 CSV 対 SQL

ストレージの最良のデフォルトが、Parquet です — 列指向、圧縮、dtype 保証です(CSV が dtype を失い、毎回のロードで再推論を強制します)。短命のキャッシュに最速なのが、Feather です(Apache Arrow 形式、シリアライズのオーバーヘッドなし)。便利だが Python/pandas のバージョン間で壊れるのが、Pickle です。データが共有されサーバー側のクエリを必要とするときは、SQL を。

pandas
# CSV: human-readable, slow, loses dtypes, large
df.to_csv("data.csv", index=False)
df = pd.read_csv("data.csv")  # re-infers dtypes (slow, error-prone)

# Parquet: binary, fast, preserves dtypes, compressed (best for storage)
df.to_parquet("data.parquet")
df = pd.read_parquet("data.parquet")  # dtypes preserved exactly

# Feather: fastest for short-lived storage (Apache Arrow)
df.to_feather("data.feather")  # requires a RangeIndex
df = pd.read_feather("data.feather")

# Pickle: Python-specific, fast, but version-fragile
df.to_pickle("data.pkl")
df = pd.read_pickle("data.pkl")

# SQL: shared, queryable, but slower for bulk reads
df.to_sql("table", engine)
df = pd.read_sql("SELECT * FROM table", engine)

# Rule of thumb:
# - CSV for human exchange
# - Parquet for storage/archival (best default)
# - Feather for fast cache between Python processes
# - SQL for shared, queryable data
15

時系列分析

DatetimeIndex の設定

DatetimeIndex から始まるのが、pandas の時系列作業です — 日付の列をインデックスへ設定し、ソートしましょう。その後、文字列でスライスでき(6 月すべてには df.loc['2024-06'])、resample/rolling/shift が使えます。非常に便利なのが、部分的な文字列のインデックスです。設定後、インデックスは必ずソートしましょう。ソートされたインデックスを要求するのが、多くの時系列のメソッドです。

pandas
# Ensure the date column is datetime, then set as index
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date").sort_index()

# Now you can slice by date strings
df.loc["2024"]                 # all of 2024
df.loc["2024-06"]              # June 2024
df.loc["2024-06-01":"2024-06-15"]  # date range (inclusive)

# Partial string indexing on Series
s = df["value"]
s["2024-06-15"]

# Filter with date strings
df[df.index >= "2024-01-01"]

# A DatetimeIndex unlocks resample, rolling, shift, etc.

実践でのリサンプリング

時系列の groupby が、resample です — 「MS」(月開始)、「ME」(月終了)、「QE」(四半期終了)、「W」(週次)です。カテゴリごとのリサンプリングのためには(都市ごとの週次の売上など)、groupby と組み合わせましょう。欠損した時間期間のための行を(NaN で満たし)加えるのが、asfreq です — 不規則なデータのギャップの公開に有用です。各期間の最後の値を取るのが、last() の集約です。

pandas
# Daily -> monthly revenue
daily.resample("MS").sum()

# Common frequencies:
# D=day, B=business day, W=weekly, MS=month start, ME=month end,
# QS=quarter start, YE=year end, H=hour, T/min=minute, S=second

# Multiple aggregations
daily.resample("ME").agg({"sales": "sum", "users": "mean"})

# Resample per group
df.groupby("city").resample("W")["sales"].sum()

# Handle missing periods (fill gaps in the timeline)
daily.asfreq("D")           # add NaN rows for missing days
daily.asfreq("D").ffill()   # fill them

# Quarter-end reporting
daily.resample("QE").last()  # last value of each quarter

タイムゾーン

(値を変えず)naive なタイムスタンプへタイムゾーンを割り当てるのが、tz_localize で、(表示される値を変え)別のタイムゾーンへ変換するのが、tz_convert です。混同しやすい 2 つです。必ず最初に localize し、その後 convert しましょう。曖昧/欠落した時刻を作るのが、DST の遷移です — これを扱うのが、ambiguous='infer'(ソートされたデータ用)か「NaT」です。

pandas
# Localize naive timestamps (assign a timezone)
s = pd.Series(pd.date_range("2024-01-01", periods=3, freq="H"))
s_localized = s.dt.tz_localize("UTC")
s_localized = s.dt.tz_localize("America/New_York")

# Convert between timezones
s_utc = s.dt.tz_localize("UTC")
s_est = s_utc.dt.tz_convert("US/Eastern")
s_hk  = s_utc.dt.tz_convert("Asia/Hong_Kong")

# On a DatetimeIndex
idx = pd.date_range("2024-01-01", periods=3, freq="H", tz="UTC")
idx = idx.tz_convert("Asia/Shanghai")

# Remove timezone info
s_naive = s_utc.dt.tz_localize(None)

# Ambiguous times (DST fall-back): use 'infer' or 'NaT'
s.dt.tz_localize("US/Eastern", ambiguous="infer")

窓関数

不規則にサンプリングされたデータを正しく扱うのが、時間ベースの rolling 窓('7D')で、(rolling(7) の)行数窓とは違います。最近の観測をより重み付けするのが、ewm(指数加重)です — 平滑化のため財務で一般的です。グループごとの窓を計算するのが(株ごとの 7 日の移動平均など)、groupby + rolling です。groupby+rolling が作る MultiIndex を片付けるのが、reset_index です。

pandas
# Rolling window with time offset
ts.rolling("7D").mean()      # 7-day window (handles irregular sampling)

# Rolling with custom function
ts.rolling("30D").apply(lambda x: np.quantile(x, 0.95))

# Expanding window (cumulative)
ts.expanding(min_periods=10).mean()

# Exponentially weighted
ts.ewm(span=20).mean()       # like a 20-period EWMA
ts.ewm(halflife=10).mean()

# Window per group
df.groupby("city")["sales"].rolling("7D").mean().reset_index(level=0, drop=True)

# Compare rolling vs ewm for smoothing
# ewm weights recent points more — better for fast-changing series

季節性と分解

時系列をトレンド、季節、残差の成分へ分割するのが、seasonal_decompose です — 構造の理解と季節性の除去に有用です。周期の長さであるのが、period です(年次の季節性を持つ月次データでは 12)。季節パターンを明らかにするのが、index.month か index.dayofweek 上の groupby です。シリーズが自分のラグとどれほど相関するか示すのが、autocorrelation_plot です。

pandas
# Seasonal decomposition (needs statsmodels)
from statsmodels.tsa.seasonal import seasonal_decompose

# Additive model: y = trend + seasonal + residual
result = seasonal_decompose(ts, model="additive", period=12)
result.plot()
result.trend, result.seasonal, result.resid

# Multiplicative model: y = trend * seasonal * residual
result = seasonal_decompose(ts, model="multiplicative", period=12)

# Seasonal plots
ts.groupby(ts.index.month).mean()   # average by month
ts.groupby(ts.index.dayofweek).mean()  # by weekday

# Lag plot (autocorrelation check)
pd.plotting.lag_plot(ts, lag=1)
pd.plotting.autocorrelation_plot(ts)
16

可視化

基本のプロット

matplotlib 上に構築されているのが、pandas のプロットです。EDA のための素早いチャートを与えるのが、.plot アクセサです。時系列に良い line が plot() のデフォルトで、カテゴリのカウントには plot.bar()、分布には plot.hist()、関係には plot.scatter() です。出版品質のチャートには、seaborn か plotly へ切り替えましょう。しかし分析中の素早い検査には、pandas のプロットが無敵です。

pandas
import matplotlib.pyplot as plt

# Line plot (default for time series)
df["score"].plot()
df.plot(x="date", y="score")

# Bar chart
df["city"].value_counts().plot.bar()
df["city"].value_counts().plot.barh()  # horizontal

# Histogram
df["age"].plot.hist(bins=20)
df[["age", "score"]].plot.hist(alpha=0.5, bins=20)

# Scatter
df.plot.scatter(x="age", y="score", c="pass", colormap="viridis")

# Box plot (per group)
df.boxplot(column="score", by="city")

# Area, density, pie
df["city"].value_counts().plot.pie(autopct="%1.1f%%")
df["score"].plot.kde()  # kernel density estimate

plt.tight_layout(); plt.show()

Seaborn でのプロット

統計の可視化で輝くのが、Seaborn です:バイオリンプロット、ペアプロット(散布行列)、ヒートマップ、信頼区間付きの回帰線です。「色によるグループ化」(hue)をエレガントに扱うため、matplotlib では冗長です。dataset のすべてのペアごとの関係を走査する最速の方法が、pairplot です。DataFrame を必ず渡し、列名を使いましょう — tidy なデータのために設計されているのが、seaborn の API です。

pandas
import seaborn as sns
import matplotlib.pyplot as plt

# Statistical plots that pandas can't easily do
sns.histplot(df["score", kde=True])
sns.boxplot(data=df, x="city", y="score")
sns.violinplot(data=df, x="city", y="score")

# Relationships
sns.scatterplot(data=df, x="age", y="score", hue="city")
sns.pairplot(df[["age", "score", "pass"]], hue="pass")

# Correlation heatmap
sns.heatmap(df.corr(numeric_only=True), annot=True, cmap="coolwarm")

# Regression plot
sns.regplot(data=df, x="age", y="score")

# Facet grid (small multiples)
g = sns.FacetGrid(df, col="city", hue="pass")
g.map(sns.histplot, "score")

plt.tight_layout(); plt.show()

Plotly によるインタラクティブプロット

インタラクティブなチャートを作るのが、Plotly Express です(ホバーのツールチップ、ズーム、パン)— ダッシュボードや、非技術のステークホルダーとの洞察の共有に最適です。seaborn を反映するのが API です(DataFrame を渡し、列を美学へマッピングします)。自己完結したインタラクティブな HTML ファイルを保存するのが、write_html です。数百万点の純粋なパフォーマンスには datashader を、洗練には、Plotly が素晴らしいです。

pandas
import plotly.express as px

# Interactive scatter (hover, zoom, pan)
fig = px.scatter(df, x="age", y="score", color="city",
                 hover_data=["name"], title="Score vs Age")
fig.show()

# Line chart
fig = px.line(df, x="date", y="score", color="city")

# Bar
fig = px.bar(df, x="city", y="score", color="pass", barmode="group")

# Histogram
fig = px.histogram(df, x="score", color="city", marginal="box")

# Faceted
fig = px.scatter(df, x="age", y="score", facet_col="city")

# 3D
fig = px.scatter_3d(df, x="age", y="score", z="hours", color="city")

# Save as HTML (interactive, no JS needed to view)
fig.write_html("plot.html")

サブプロットとレイアウト

axes のグリッドを作るのが、plt.subplots で、プロット時にそれぞれを ax= へ渡しましょう。サブプロットをまたいで axes を整列するのが、sharex/sharey です(スケールの比較に有用)。別の y 軸上の第 2 の系列をプロットするのが、secondary_y です(価格と出来高など)。ラベルの重なりを防ぐのが、tight_layout です。サブプロットのサイジングをより細かく制御するのが、複雑なレイアウトのための gridspec です。

pandas
import matplotlib.pyplot as plt

# pandas plot on specific axes
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
df["age"].plot.hist(ax=axes[0, 0], title="Age")
df["score"].plot.hist(ax=axes[0, 1], title="Score")
df["city"].value_counts().plot.bar(ax=axes[1, 0], title="City")
df.plot.scatter(x="age", y="score", ax=axes[1, 1], title="Age vs Score")
plt.tight_layout(); plt.show()

# Shared x-axis
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6))
df["score"].plot(ax=ax1)
df["age"].plot(ax=ax2)

# Secondary y-axis
ax = df["score"].plot()
df["age"].plot(ax=ax, secondary_y=True)
ax.set_ylabel("Score"); ax.right_ax.set_ylabel("Age")

DataFrame のスタイリング

Jupyter と HTML での DataFrame の描画をカスタマイズするのが、Styler のオブジェクトです。一目で表を読みやすくするのが、グラデーション、セル内のバー、条件付きの整形です。数値の表示(小数、パーセンテージ)を制御するのが、format です。表示時に計算され(データを変えません)、レポートのため HTML へエクスポートできます。セルごとに関数を適用するのが、applymap で、行/列ごとに機能するのが、apply です。

pandas
# Style a DataFrame for HTML/Jupyter display
styled = df.style.highlight_max(color="lightgreen")
styled = df.style.highlight_min(color="lightcoral")
styled = df.style.background_gradient(cmap="Blues", subset=["score"])

# Bar charts inside cells
df.style.bar(subset=["score"], color="#5fba7d")

# Format numbers
df.style.format({"score": "{:.2f}", "age": "{:.0f}"})
df.style.format({"score": "{:.2%}"})  # as percentage

# Conditional formatting
def color_neg_red(val):
    color = "red" if val < 0 else "black"
    return f"color: {color}"
df.style.applymap(color_neg_red, subset=["change"])

# Combine styles
(df.style
   .format({"score": "{:.2f}"})
   .background_gradient(cmap="RdYlGn", subset=["score"])
   .set_caption("Student Scores"))

# Export to HTML
styled.to_html("table.html")
17

エクスポートと整形

表示の整形

コンソール/Jupyter での pandas の印刷を制御するのが、表示のオプションです — より多くを見るには max_rows/max_columns を増やし、一貫した小数のため float_format を設定しましょう。設定を一時的に変える(後に復元する)コンテキストマネージャーが、option_context です。環境をグローバルに変えず 1 回限りの検査に完璧です。よく使う設定は、起動スクリプトへ置きましょう。

pandas
# Global display options
pd.set_option("display.max_rows", 100)
pd.set_option("display.max_columns", 50)
pd.set_option("display.width", 1000)
pd.set_option("display.max_colwidth", 100)
pd.set_option("display.float_format", "{:.2f}".format)

# Reset to defaults
pd.reset_option("display.max_rows")

# Float formatting only for one operation
with pd.option_context("display.float_format", "{:.2f}".format):
    print(df)

# Temporarily show more rows
with pd.option_context("display.max_rows", None):
    print(df.head(100))

複数形式へのエクスポート

README とドキュメントのための、GitHub 対応の表を作るのが、to_markdown です。Web ページへの埋め込みが、to_html で、学術論文には to_latex です。API のための、dict のリスト(JSON 風)への変換が、to_dict(orient='records') です。各形式にオプションがあります — ドキュメントを探索しましょう。Excel では、formatting の数式、条件付きの形式、チャートに対応するのが、engine='openpyxl' です。

pandas
# CSV
df.to_csv("out.csv", index=False)
df.to_csv("out.tsv", sep="\t", index=False)

# Excel with formatting (needs openpyxl)
with pd.ExcelWriter("out.xlsx", engine="openpyxl") as w:
    df.to_excel(w, sheet_name="data", index=False)
    summary.to_excel(w, sheet_name="summary")

# Markdown (great for docs/reports)
print(df.to_markdown(index=False))
df.to_markdown("table.md", index=False)

# HTML
df.to_html("table.html", index=False, classes="table")

# LaTeX
print(df.to_latex(index=False, caption="Results"))

# JSON
df.to_json("out.json", orient="records", indent=2, date_format="iso")

# Dict / records
df.to_dict(orient="records")  # list of dicts
df.to_dict(orient="list")     # dict of lists

クリップボードと文字列

Excel/Google Sheets へ直接貼り付けられる、タブ区切りの表をコピーするのが、to_clipboard(excel=True) です — Python とスプレッドシートの間でデータを動かすのに、信じられないほど手軽です。逆が、read_clipboard です。Web ページかスプレッドシートから表をコピーし、ファイルを保存せず DataFrame へ読み込みましょう。ロギングのためのプレーンテキストの表現を与えるのが、to_string です。

pandas
# Copy a DataFrame to the clipboard (paste into Excel/Sheets)
df.to_clipboard(index=False, excel=True)

# Read from clipboard (paste a table from a spreadsheet/webpage)
df = pd.read_clipboard()

# Convert to string with formatting
print(df.to_string(index=False))
print(df.to_string(max_rows=10))

# Pretty-print in Jupyter
from IPython.display import display
display(df.head(10))

# Render a Series as a string
print(s.to_string())

# Quick peek at value (useful in debugging)
df.head().to_dict("records")

Excel の整形

プログラム的に Excel の出力をスタイルできるのが、openpyxl です — 太字のヘッダー、列幅、フリーズペイン、条件付きの整形、数式です。書き込み後に、writer.book 経由でワークブックへ、writer.sheets 経由でシートへアクセスしましょう。手動の幅の計算を必要とするのが、列の自動サイズ変更です(ファイル書き込み時に Excel が自動で行いません)。スクロール中ヘッダーが見えるまま保つのが、フリーズペインです。

pandas
from openpyxl.styles import Font, PatternFill
from openpyxl.utils import get_column_letter

# Write with conditional formatting
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
    df.to_excel(writer, sheet_name="Data", index=False)

    # Access the workbook to style
    wb = writer.book
    ws = writer.sheets["Data"]

    # Bold header
    for cell in ws[1]:
        cell.font = Font(bold=True, color="FFFFFF")
        cell.fill = PatternFill("solid", fgColor="4472C4")

    # Auto-size columns
    for col in ws.columns:
        max_len = max(len(str(c.value)) for c in col if c.value is not None)
        ws.column_dimensions[get_column_letter(col[0].column)].width = max_len + 2

    # Freeze header row
    ws.freeze_panes = "A2"

再現可能なノートブック

ノートブックのヘッダー(インポート、オプション、シード、バージョン確認)の標準化で、分析が再現可能になり、デバッグ時間が節約されます。pandas/numpy/python のバージョンを報告するのが、pd.show_versions() です — バグレポートへ貼り付けましょう。shape、dtype、head、欠損を印刷する check_df のヘルパーが、任意の新しい dataset の最初の見方を標準化します。特定の警告カテゴリだけを抑制し、決して全部ではありません。

pandas
# At the top of every analysis notebook
import pandas as pd
import numpy as np
pd.set_option("display.max_columns", None)
pd.set_option("display.float_format", "{:.4f}".format)

# Set a seed for reproducibility
np.random.seed(42)

# Show versions for reproducibility
pd.show_versions()

# Common imports grouped
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")

# Suppress chained-assignment warnings cleanly
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

# Validate data on load
def check_df(df, name="df"):
    print(f"=== {name} ===")
    print(f"Shape: {df.shape}")
    print(df.dtypes)
    print(df.head())
    print(df.isnull().sum())
check_df(df)
18

よくある落とし穴

SettingWithCopyWarning

あなたの代入が永続しないかもしれないことを pandas が伝えるのが、SettingWithCopyWarning です。一時的なコピーを修正し得るのが、チェーンされたインデックス(df[mask]['col']=x)です。修正は、条件付き代入のための常に .loc[row_mask, col_name] = value です。部分集合を作り修正するときは、明示的にするため .copy() を使いましょう。開発中には、これらのバグをエラーとして捉えるため、警告を「raise」へ設定しましょう。

pandas
# BAD: chained indexing — may not modify df
df[df["age"] > 30]["city"] = "NYC"   # SettingWithCopyWarning

# GOOD: single .loc assignment
df.loc[df["age"] > 30, "city"] = "NYC"

# When subsetting, be explicit about copy vs view
subset = df[df["age"] > 30].copy()   # explicit copy
subset["city"] = "NYC"               # safe — modifies subset only

# Detect the warning
pd.set_option("mode.chained_assignment", "warn")   # default
pd.set_option("mode.chained_assignment", "raise")  # error (dev mode)
pd.set_option("mode.chained_assignment", None)     # suppress

# Rule: if you're going to modify, use .loc or .copy() first

インデックス整列の驚き

pandas の超能力と最大の落とし穴が、インデックスの整列です。Series を列へ割り当てるとき、位置ではなくインデックスにより pandas がマッチするため — あなたの Series が異なるインデックスを持てば、NaN か誤った値が得られます。位置で割り当てるには .values を、インデックスを整列させるには先に reset_index を使います。サイレントである(警告なし)のが、このバグで、最もよくある pandas の間違いの一つです。

pandas
# Adding Series aligns on index — NaN where they don't match
s1 = pd.Series([1, 2, 3], index=["a", "b", "c"])
s2 = pd.Series([10, 20, 30], index=["b", "c", "d"])
s1 + s2
# a     NaN
# b    12.0
# c    33.0
# d     NaN

# When assigning a Series to a column, alignment happens by index
df["new"] = some_series   # rows matched by INDEX, not position!

# To force positional alignment, use .values
df["new"] = some_series.values   # assign by position

# After sorting/resetting, indexes may not match
df1 = df.sort_values("age")
df1["rank"] = range(len(df1))   # WRONG if index isn't 0..n-1
df1["rank"] = np.arange(len(df1))  # also WRONG — aligns on index
df1["rank"] = pd.Series(range(len(df1)), index=df1.index)  # correct
# Or simply:
df1 = df1.reset_index(drop=True)
df1["rank"] = range(len(df1))

inplace 対再代入

inplace=True から離れ、関数型の再assignment へ動いているのが、pandas のコミュニティです。これが、メソッドのチェーン(読みやすいパイプライン)を可能にし、より予測可能です。メモリをめったに節約しないのが、inplace です(pandas がしばしばいずれにせよコピーします)。上から下へ読めるのが、(df.method().method().method() の)チェーンスタイルで、モダンな慣用句です。実際のメモリの利得を測ったときだけ、inplace を。

pandas
# Two equivalent styles:
df = df.sort_values("age")        # reassign (returns new df)
df.sort_values("age", inplace=True)  # modify in place

# Most pandas methods return a new object (functional style).
# inplace=True modifies the object — but:
# 1. It's being deprecated in some methods
# 2. It can prevent method chaining
# 3. It sometimes still makes a copy under the hood

# Prefer functional style for chaining:
(df
   .sort_values("age")
   .reset_index(drop=True)
   .rename(columns={"old": "new"}))

# inplace is fine for memory savings on huge DataFrames,
# but rarely matters otherwise.

可変なデフォルト引数

行ごとの DataFrame の成長(ループ内の df.append や pd.concat)が O(n²) です — 各 append がフレーム全体をコピーします。常にリストへ行を集め、その後 DataFrame を 1 回構築しましょう。同じことが、Python の可変なデフォルト引数(リスト、dict)に適用され — 呼び出し間で共有され、クラシックな Python のバグです。センチネルとして None を使うようにし、関数内で初期化しましょう。

pandas
# BAD: default mutable args are shared across calls
def add_row(df, new_data=[]):   # NEVER use mutable defaults
    new_data.append(1)
    return df

# GOOD: use None
def add_row(df, new_data=None):
    if new_data is None:
        new_data = []
    ...

# Building a DataFrame row by row (SLOW — anti-pattern)
df = pd.DataFrame()
for item in items:
    df = pd.append(df, item)  # deprecation + O(n^2)

# GOOD: build a list of records, then construct once
records = []
for item in items:
    records.append({"name": item.name, "value": item.value})
df = pd.DataFrame(records)

# Or use from_records
df = pd.DataFrame.from_records(items, columns=["name", "value"])

NaN の伝播

NaN が決して自分自身と等しくないこと(NaN == NaN が False)を覚えましょう — 欠損値の検出には isna() を使い、決して == ではありません。デフォルトで NaN をスキップするのが(sum、mean)、集約ですが、それを伝播させるには skipna=False を渡しましょう。いずれかの NaN がある整数列が、float64 へ upcast されます(numpy の int が NaN を保持できないため)です。NaN 付きで整数を保つには、nullable な「Int64」の dtype(大文字の I)を使いましょう。

pandas
# NaN propagates through most operations
np.nan + 1          # nan
np.nan > 0          # False
pd.Series([1, 2, np.nan]).sum()    # 3.0 (skips NaN by default)
pd.Series([1, 2, np.nan]).mean()   # 1.5

# Some operations DON'T skip NaN
pd.Series([1, 2, np.nan]).sum(skipna=False)  # nan

# Comparisons with NaN are always False
pd.Series([1, np.nan]) == pd.Series([1, np.nan])
# [True, False]  — NaN != NaN!

# Check for NaN correctly
s.isna()            # True for NaN
s.isnull()          # alias
s == np.nan         # WRONG — always False!
s.fillna(0) == 0    # check after filling

# Integer columns with NaN become float
s = pd.Series([1, 2, None])   # becomes float64: [1.0, 2.0, NaN]
# Use nullable Int64 to keep integer with NaN
s = pd.Series([1, 2, None], dtype="Int64")
19

実世界のパターン

EDA テンプレート

標準化された EDA の関数により、モデリングの前に、shape、dtype、欠損、分布、重複を必ず確認できます。早い段階で間違った dtype(文字列としての数値)、隠れた欠損(-999 のようなセンチネル値)、予想外の重複を捉えることが、下流のデバッグの何時間もを節約します。新しい dataset のたびに、最初のステップとしてこれを実行しましょう。

pandas
import pandas as pd
import numpy as np

def eda(df, name="df"):
    print(f"=== {name} ===")
    print(f"Shape: {df.shape}")
    print("\n--- dtypes ---")
    print(df.dtypes)
    print("\n--- head ---")
    print(df.head())
    print("\n--- missing ---")
    print(df.isnull().sum())
    print("\n--- numeric summary ---")
    print(df.describe())
    print("\n--- categorical summary ---")
    print(df.describe(include="object"))
    print("\n--- duplicates ---")
    print(f"{df.duplicated().sum()} duplicate rows")

# Usage
eda(df)

# Per-column deep dive
for col in df.columns:
    print(f"\n### {col}")
    print(f"dtype: {df[col].dtype}")
    print(f"unique: {df[col].nunique()}")
    if df[col].dtype == "object":
        print(df[col].value_counts().head(10))
    else:
        print(df[col].describe())

クリーンアップのパイプライン構築

クリーンアップを再現可能でテスト可能にするのが、メソッドのチェーン(.pipe / .assign / .dropna のパイプライン)です。各ステップが純関数であり、任意の時点で検査が簡単です。引用の頭痛を避けるため、早く snake_case へ列を改名しましょう。サイレントな失敗を捉えるのが(すべての日付のパース失敗など)、末尾の assert 文です。新しいデータバッチで再利用できるよう、パイプラインを関数で包みましょう。

pandas
def clean(df):
    """A reusable cleaning pipeline."""
    return (df
        # Standardize column names
        .rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
        # Drop empty columns
        .dropna(axis=1, how="all")
        # Parse dates
        .assign(date=lambda d: pd.to_datetime(d["date"], errors="coerce"))
        # Numeric coercion
        .assign(amount=lambda d: pd.to_numeric(d["amount"], errors="coerce"))
        # Fill missing
        .fillna({"category": "unknown"})
        # Dedupe
        .drop_duplicates()
        # Reset index
        .reset_index(drop=True)
    )

df_clean = clean(df_raw)

# Verify
assert df_clean["date"].notnull().all(), "Some dates failed to parse"
assert len(df_clean) <= len(df_raw), "Cleaning should not add rows"

ピボットテーブルの分析

アナリストのスイスアーミーナイフが、pivot_table です — 瞬時の洞察のために、合計のための margins=True と、ヒートマップと組み合わせましょう。さらなる処理のために、tidy な長い形式へ戻すのが、逆(melt)です。ビジネスのレポートで極めてよくあるのが、「グループごとのトップ N」のパターン(ソートして groupby の head)です。

pandas
# Multi-dimensional analysis in one shot
pivot = pd.pivot_table(
    df,
    values="revenue",
    index=["region", "product"],
    columns=["quarter"],
    aggfunc="sum",
    fill_value=0,
    margins=True,         # add row/column totals
    margins_name="Total",
)

# Heatmap of the pivot
import seaborn as sns
sns.heatmap(pivot, annot=True, fmt=".0f", cmap="YlGnBu")

# Convert back to long
long = pivot.reset_index().melt(
    id_vars=["region", "product"],
    var_name="quarter",
    value_name="revenue",
)

# Top product per region
top = (df
    .groupby(["region", "product"])["revenue"].sum()
    .reset_index()
    .sort_values("revenue", ascending=False)
    .groupby("region").head(1))

ML のための特徴エンジニアリング

ドメイン知識が pandas と出会うのが、特徴エンジニアリングです:エンティティごとの集約(顧客の生涯支出)、比率(月ごとの支出)、時間ベースの特徴(在籍期間)、ビン化されたカテゴリです。エンティティ ID により、集約された特徴をメインのフレームへマージし戻しましょう。線形モデルのための one-hot エンコードが、get_dummies です。学習時と推論時に同じ変換が適用されるよう、関数で包みましょう。

pandas
def add_features(df):
    """Add features for a churn model."""
    out = df.copy()

    # Time-based features
    out["tenure_years"] = out["tenure_months"] / 12
    out["is_new_customer"] = (out["tenure_months"] < 12).astype(int)

    # Aggregations per customer (need transaction history)
    # txns is a separate transactions DataFrame
    agg = txns.groupby("customer_id").agg(
        total_spend=("amount", "sum"),
        txn_count=("amount", "count"),
        avg_txn=("amount", "mean"),
        last_txn_date=("date", "max"),
    ).reset_index()
    out = out.merge(agg, on="customer_id", how="left")

    # Ratio features
    out["spend_per_month"] = out["total_spend"] / out["tenure_months"]

    # Binning
    out["age_group"] = pd.cut(out["age"], bins=[0,25,40,60,100],
                              labels=["young","adult","mid","senior"])

    # Encode categoricals
    out = pd.get_dummies(out, columns=["age_group", "plan"], drop_first=True)

    return out

df_ml = add_features(df)

乱れた CSV の読み取り

乱雑なのが、実世界の CSV です:間違ったエンコーディング(utf-8 が失敗したら latin-1 か cp1252 を試す)、ヨーロッパの小数コンマ(decimal=',')、ヘッダーの前のメタデータ行(skiprows)、センチネルの null 値(na_values)です。必要な列だけをロードし、幅広のファイルでメモリを節約するのが、usecols です。盲目に読む前に、テキストエディタで未知の CSV の最初の数行を必ず検査しましょう。

pandas
# Common CSV issues and fixes

# Bad encoding
df = pd.read_csv("data.csv", encoding="latin-1")  # or utf-8-sig, cp1252

# Wrong separator
df = pd.read_csv("data.tsv", sep="\t")
df = pd.read_csv("data.csv", sep=";", decimal=",")  # European format

# Skip metadata rows at the top
df = pd.read_csv("data.csv", skiprows=3)

# Multiple header rows
df = pd.read_csv("data.csv", header=[0, 1])

# Custom NA values
df = pd.read_csv("data.csv", na_values=["?", "N/A", "NULL", -999])

# Parse dates with multiple formats
df = pd.read_csv("data.csv", parse_dates=["date"], dayfirst=True)

# Only load specific columns (saves memory)
df = pd.read_csv("data.csv", usecols=["id", "date", "amount"])

# Handle quoted fields with commas/newlines
df = pd.read_csv("data.csv", quotechar='"', escapechar="\\")
20

窓操作の深掘り

カスタム関数での Rolling

C 最適化で速いのが、組み込みの rolling 集約(mean、std、median、quantile)です。柔軟だが遅いのが(窓ごとの Python コールバック)、カスタムの apply 関数です。加重平均や回帰のためには、中に numpy 操作付きの apply を使いましょう。numpy 配列を渡すのが(速い)、raw=True(デフォルト)で、インデックスを必要とするなら Series を渡すのが、raw=False です。

pandas
s = pd.Series(range(20), dtype=float)

# Built-in aggregations (fast, C-optimized)
s.rolling(5).mean()
s.rolling(5).std()
s.rolling(5).median()
s.rolling(5).quantile(0.75)
s.rolling(5).sum()

# Custom function (slower, but flexible)
s.rolling(5).apply(lambda x: x.max() - x.min())

# Weighted rolling average
weights = np.array([0.1, 0.2, 0.3, 0.25, 0.15])
s.rolling(5).apply(lambda x: np.dot(x, weights))

# Rolling regression (slope over window)
def slope(x):
    return np.polyfit(range(len(x)), x, 1)[0]
s.rolling(10).apply(slope)

# raw=False passes Series (with index) to the function
s.rolling(5).apply(lambda x: x.iloc[-1] / x.iloc[0], raw=False)

時間ベースの窓

不規則にサンプリングされたデータを正しく扱うのが、時間ベースの窓('7D')です — 固定の行数でなく、時間範囲内のすべての点を含めます。ギャップのある実世界の時系列には、これが不可欠です。現在の点に窓を中心に置くのが、center=True です(平滑化に有用)。現在の点を除外するのが、closed='left' です(「未来」から特徴を計算する際の漏れの回避)。

pandas
# Row-count vs time-based windows
ts = pd.Series(range(100), index=pd.date_range("2024-01-01", periods=100, freq="D"))

# Row-count: exactly 7 rows (may span more than 7 days if data is irregular)
ts.rolling(7).mean()

# Time-based: all rows within the last 7 days (handles gaps)
ts.rolling("7D").mean()

# Time-based is essential for irregular time series
irregular = pd.Series([1, 2, 3],
    index=pd.to_datetime(["2024-01-01", "2024-01-05", "2024-01-15"]))
irregular.rolling("7D").sum()   # 1, 3, 3 (third is just itself, no neighbors in 7d)

# Center the window
ts.rolling("7D", center=True).mean()  # window centered on current point

# Closed controls which endpoints are included
ts.rolling("7D", closed="left").mean()  # exclude current point

Expanding と EWMA

開始から現在の点まで、すべてのデータの上で統計を計算するのが、expanding です — 累積のベンチマークや、動く極値に有用です。最近の観測をより重み付けするのが、ewm(指数加重)です — 財務の平滑化(EWMA)の標準です。直感的なのが、span です(N 期間の移動平均に似ます)。生の平滑化係数が、alpha です。最近の変化に、単純な移動平均より速く反応するのが、EWMA です。

pandas
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)

# Expanding: window grows from the start
s.expanding(min_periods=2).mean()   # cumulative mean
s.expanding().max()                 # running maximum
s.expanding().std()

# Exponentially weighted moving average
s.ewm(span=5).mean()       # span=N similar to N-period moving avg
s.ewm(alpha=0.3).mean()    # alpha = smoothing factor (0-1)
s.ewm(halflife=3).mean()   # halflife: weight halves every N periods

# EWMA volatility (finance)
returns.ewm(span=20).std()  # 20-period EWMA volatility

# Relationship: span = (2/alpha) - 1
# Higher alpha/span = more responsive to recent data

累積の操作

直接的な累積のメソッドが、cumsum、cummax、cummin、cumprod です — よくあるケースには、expanding より速いです。groupby と組み合わせると、グループごとの累計が計算されます(顧客ごとの running 残高など)。セッション/セグメントの識別子を作るトリックが、真偽条件上の cumsum です — イベント間のエピソードへ時系列を分割するのに有用です。

pandas
s = pd.Series([1, 2, 3, 4, 5])

# Direct cumulative methods (faster than expanding)
s.cumsum()    # [1, 3, 6, 10, 15]
s.cummax()    # [1, 2, 3, 4, 5]
s.cummin()    # [1, 1, 1, 1, 1]
s.cumprod()   # [1, 2, 6, 24, 120]

# Cumulative within groups
df["running_total"] = df.groupby("customer")["amount"].cumsum()
df["rank_in_group"] = df.groupby("customer")["amount"].rank(ascending=False)
df["pct_of_total"] = df["amount"] / df.groupby("customer")["amount"].transform("sum")

# Cumulative count of condition
df["days_since_event"] = (df["event"] == 1).cumsum()
df["event_number"] = df.groupby(
    (df["event"] == 1).cumsum()
).cumcount()

複数出力の Rolling Apply

複数の rolling 統計のためには、各々を別々に計算する方が(window.mean()、window.std())、Series を返す単一の apply より、明快でしばしば速いです。トレンドの周りの信頼帯を構築させられるのが、rolling の分位点です(q10/q90)。プロットや ML モデルへの供給前の典型的なパターンが、rolling 統計の DataFrame の作成です。

pandas
# Apply a function returning multiple values per window
def rolling_stats(x):
    return pd.Series({
        "mean": x.mean(),
        "std": x.std(),
        "min": x.min(),
        "max": x.max(),
    })

stats = s.rolling(10).apply(rolling_stats, raw=False)
# This creates a DataFrame with one row per window, columns = the Series index

# Alternative: compute each separately (often clearer)
window = s.rolling(10)
result = pd.DataFrame({
    "mean": window.mean(),
    "std":  window.std(),
    "min":  window.min(),
    "max":  window.max(),
})

# Rolling quantiles
q = pd.DataFrame({
    "q10": s.rolling(20).quantile(0.1),
    "q50": s.rolling(20).quantile(0.5),
    "q90": s.rolling(20).quantile(0.9),
})

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.