LoginSignup
1
1

More than 1 year has passed since last update.

pandera の SchemaModel で MultiIndex の DataFrame をバリデーションする方法

Posted at

やりたいこと

MultiIndexのDataFrameをpandera.SchemaModelを使ってバリデーションしたい

DataFrame例
import pandas as pd

idxs = pd.MultiIndex.from_product([['foo', 'bar', 'buz'], [0, 1, 2]], names=['idx_0', 'idx_1'])
cols = pd.MultiIndex.from_product([['ham'], ['bacon', 'eggs']], names=['col_0', 'col_1'])
data = list(zip([100., 200., 300.], 'abc')) * 3
df = pd.DataFrame(data=data, index=idxs, columns=cols)
df
col_0          ham     
col_1        bacon eggs
idx_0 idx_1            
foo   0      100.0    a
      1      200.0    b
      2      300.0    c
bar   0      100.0    a
      1      200.0    b
      2      300.0    c
buz   0      100.0    a
      1      200.0    b
      2      300.0    c

結論

MultiIndex Indexes

  • df.index.namesの各インデックス名で指定
  • pandera.typing.Indexで型指定

MultiIndex Columns

  • pandera.Field(alias=)でカラム名をタプルで指定
  • pandera.typing.Seriesで型指定

Schema Modelsによるバリデーション

Schema例
import pandera as pa
from pandera.typing import Index, Series

# スキーマモデルの定義
class MultiIndexSchema(pa.SchemaModel):
    idx_0: Index[str] = pa.Field(str_length=3)
    idx_1: Index[float] = pa.Field(ge=0, le=2)
    col_00: Series[int] = pa.Field(alias=('ham', 'bacon'), coerce=True)
    col_01: Series[str] = pa.Field(alias=('ham', 'eggs'))

    class Config:
        multiindex_name = 'hogehoge'
        multiindex_strict = True
        multiindex_coerce = True

# バリデーション実行
MultiIndexSchema.validate(df)
MultiIndexSchema.validate(df)
col_0         ham     
col_1       bacon eggs
idx_0 idx_1           
foo   0.0     100    a
      1.0     200    b
      2.0     300    c
bar   0.0     100    a
      1.0     200    b
      2.0     300    c
buz   0.0     100    a
      1.0     200    b
      2.0     300    c

参考

公式チュートリアル

pandera.SchemaModelを使ったMultiIndexのバリデーション

pandera.DataFrameSchemaを使ったMultiIndexのバリデーション

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1