Pandas カテゴリ型(Categorical)

Categorical は、Pandas で有限のカテゴリ値を処理するためのデータ型で、性別、学歴、等級などの列挙型データの処理に特に適しています。カテゴリ型はメモリ使用量を大幅に削減し、計算パフォーマンスを向上させることができます。


Categorical データの作成

Series から作成

例

import pandas as pd

# カテゴリデータを作成
s = pd.Series(["男", "女", "男", "女", "男"], dtype="category")
print("基本カテゴリデータ:")
print(s)
print(f"型: {s.dtype}")
print()

# カテゴリの順序を指定
s2 = pd.Series(
    ["低", "中", "高", "中", "低"],
    dtype=pd.CategoricalDtype(categories=["低", "中", "高"], ordered=True)
)
print("順序付きカテゴリ:")
print(s2)
print(f"カテゴリ順序: {s2.dtype.categories.tolist()}")

リストから作成

例

import pandas as pd

# pd.Categorical を使用
categories = pd.Categorical(
    ["甲", "乙", "甲", "丙", "乙"],
    categories=["甲", "乙", "丙"]
)

s = pd.Series(categories)
print("Categorical から作成:")
print(s)

カテゴリの属性とメソッド

カテゴリ情報へのアクセス

例

import pandas as pd

s = pd.Series(
    ["低", "中", "高", "中", "低"],
    dtype=pd.CategoricalDtype(categories=["低", "中", "高"], ordered=True)
)

# カテゴリ属性
print(f"カテゴリ: {s.dtype.categories.tolist()}")
print(f"順序付きかどうか: {s.dtype.ordered}")
print()

# 各カテゴリの数を集計
print("カテゴリ集計:")
print(s.value_counts())

カテゴリの変更

例

import pandas as pd

s = pd.Series(["A", "B", "C", "A", "B"], dtype="category")

print("カテゴリ名の変更:")
s2 = s.cat.rename_categories({"A": "優秀", "B": "良好", "C": "合格"})
print(s2)
print()

# 新しいカテゴリを追加
print("カテゴリの追加:")
s3 = s.cat.add_categories(["D"])
print(s3.dtype.categories.tolist())
print()

# カテゴリを削除
print("カテゴリの削除:")
s4 = s.cat.remove_categories(["C"])
print(s4.dtype.categories.tolist())

順序付きカテゴリ

順序付きカテゴリは比較操作をサポートし、大小の順序がある分類データに適しています。

例

import pandas as pd

# 順序付きカテゴリを作成
s = pd.Series(
    ["低", "中", "高", "高", "低", "中"],
    dtype=pd.CategoricalDtype(categories=["低", "中", "高"], ordered=True)
)

# 比較操作
print("高 > 中:", s > "中")
print("中 > 低:", s > "低")
print()

# ソート
print("ソート後:")
print(s.sort_values())

実践:データのグループ化

例

import pandas as pd

# ユーザー等級データをシミュレート
users = pd.DataFrame({
    "ユーザーID": range(1, 1001),
    "等級": pd.Categorical(
        ["VIP"] * 100 + ["ゴールドカード"] * 300 + ["シルバーカード"] * 400 + ["普通"] * 200,
        categories=["普通", "シルバーカード", "ゴールドカード", "VIP"],
        ordered=True
    ),
    "消費額": [1000, 500, 100, 50] * 250
})

print("ユーザー等級分布:")
print(users["等級"].value_counts().sort_index())
print()

# 等級ごとにグループ化して集計
print("等級別の集計:")
print(users.groupby("等級", observed=True)["消費額"].sum())

メモリ最適化

カテゴリ型は、文字列データのメモリ使用量を大幅に削減できます。

例

import pandas as pd
import numpy as np

# 大量に重複した文字列データを作成
np.random.seed(42)
s_str = pd.Series(np.random.choice(["北京", "上海", "広州", "深セン"], 1000000))

# カテゴリ型に変換
s_cat = s_str.astype("category")

# メモリ比較
print(f"文字列型メモリ: {s_str.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
print(f"カテゴリ型メモリ: {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
print(f"削減率: {(1 - s_cat.memory_usage(deep=True) / s_str.memory_usage(deep=True)) * 100:.1f}%")

データに大量の重複した文字列値がある場合、カテゴリ型を使用するとメモリ使用量を大幅に削減でき、大規模データセットに特に適しています。

その他の拡張