review_wrangling

データ前処理(wrangling)による変更点を要約して、レビュー形式の文字列として出力する関数です。
概要
この関数は、前処理の前後(before / after)の DataFrame を比較し、変更点をユーザーが読みやすいレビュー形式の文字列として返します。
review_wrangling(
before: IntoFrameT,
after: IntoFrameT,
items: List[str] = ['shape', 'col_addition', 'casting', 'missing', 'category'],
title: str = 'Review of wrangling',
abbreviate: bool = True,
max_columns: Optional[int] = None,
max_categories: Optional[int] = None,
max_width: int = 80
) -> str引数 Argument
before:IntoFrameT(必須)
前処理(wrangling)を行う前のデータフレーム。narwhals が受け入れ可能な DataFrame 互換オブジェクト
(例:pandas.DataFrame、polars.DataFrame、pyarrow.Table)を指定できます。after:IntoFrameT(必須)
前処理(wrangling)を行った後のデータフレーム。items:List of str
- 出力に含めるレビュー項目と、その表示順序を指定するリスト。
itemsの要素は次の文字列から選択できます。:'shape': データフレームの形状(行数・列数)の変化'col_addition': 列の追加および削除'casting': 列のデータ型(dtype)の変更'missing': 欠損値の増加と減少'category': カテゴリ変数における水準(レベル)の追加および削除'numeric': ASCII 文字列の箱ひげ図で要約された数値変数の分布'all': 上記の全てのレビュー項目
レビューセクションはitemsで指定された順序で生成されます。省略された場合、'numeric'を除いた5項目がデフォルトとして使用されます。
- 出力に含めるレビュー項目と、その表示順序を指定するリスト。
title:str
出力されるレビューテキストのタイトル。空でない文字列を指定した場合、タイトルとともにヘッダーとフッターが追加されます。abbreviate:bool
列名やカテゴリー水準の一覧を省略表示するかどうかを指定します。Falseを指定した場合、省略は行われず、すべての項目が表示されます。デフォルトはTrueです。max_columns:int
列の追加・削除を報告する際に表示する列名の最大数。指定された場合、abbreviate = Trueのときに限り、文字数ではなく列数を基準として省略が行われます。Noneの場合は文字数(max_width)に基づいて省略されます。max_categories:int
カテゴリー変数の水準の変化を報告する際に、表示する水準の最大数。指定された場合、abbreviate=Trueのときに限り、文字数ではなく水準数を基準として省略が行われます。Noneの場合は文字数(max_width)に基づいて省略されます。max_width:int
abbreviate=Trueかつ対応するmax_*引数が None の場合に使用される、省略判定のための最大文字数。デフォルトは 80 です。
返り値 Value
before と after の差分を要約した、整形済みの文字列。レビューには items 引数で指定された項目が含まれます。
使用例 Examples
import py4stats as py4st
from palmerpenguins import load_penguins
before = load_penguins() # サンプルデータの読み込
after = before.copy().dropna()review_wrangling() 関数は前処理前後のデータフレームを比較し、上記の4項目に関する変化をレビューとして出力します。各項目の変化を報告しますが、変化がなかった場合にも変化がなかったことを報告する仕様となっています。
print(py4st.review_wrangling(before, after))
#> =================== Review of wrangling ====================
#> The shape of DataFrame:
#> Rows: before 344 -> after 333 (-11)
#> Cols: before 8 -> after 8 (No change)
#>
#> No columns were added or removed.
#>
#> No existing columns had their type changed.
#>
#> No existing columns increased the number of missing values.
#>
#> Decrease in missing values:
#> bill_length_mm before 2 (0.58%) -> after 0 (0.00%)
#> bill_depth_mm before 2 (0.58%) -> after 0 (0.00%)
#> flipper_length_mm before 2 (0.58%) -> after 0 (0.00%)
#> body_mass_g before 2 (0.58%) -> after 0 (0.00%)
#> sex before 11 (3.20%) -> after 0 (0.00%)
#>
#> The following columns show changes in categories:
#> sex:
#> addition: None
#> removal: 'nan'
#> ============================================================次に、先ほどのデータに、列の追加や削除、型変換、レコードの抽出といった前処理を加えてみましょう。
after = py4st.filtering_out(after, 'sex')
s = after['body_mass_g']
after['heavy'] = np.where(s >= s.quantile(0.75), True, False) # 列の追加 1
after['const'] = 1 # 列の追加 2
after['species'] = pd.Categorical(after['species']) # 列の型変換 1
after['year'] = after['year'].astype(float) # 列の型変換 2
after['flipper_length_mm'] = py4st.set_miss( # 欠測値の挿入
after['flipper_length_mm'], prop = 0.1,
random_state = 1230
)
after = after.query('species != "Adelie"') # レコードの抽出review_wrangling() では、カテゴリー変数についてユニーク値の変化を追っているため、データの抽出による暗黙的なカテゴリーの除外(e.g. species = 'Adelie' を除外したことで island = 'Torgersen' が除外された)も報告することができます。
print(py4st.review_wrangling(before, after))
#> ================== Review of wrangling ===================
#> The shape of DataFrame:
#> Rows: before 344 -> after 187 (-157)
#> Cols: before 8 -> after 9 (+1)
#>
#> Column additions and removals:
#> added: 'heavy' and 'const'
#> removed: 'sex'
#>
#> The following columns have changed their type:
#> species object -> category
#> year int64 -> float64
#>
#> Increase in missing values:
#> flipper_length_mm before 2 (0.58%) -> after 22 (11.76%)
#>
#> Decrease in missing values:
#> bill_length_mm before 2 (0.58%) -> after 0 (0.00%)
#> bill_depth_mm before 2 (0.58%) -> after 0 (0.00%)
#> body_mass_g before 2 (0.58%) -> after 0 (0.00%)
#>
#> The following columns show changes in categories:
#> species:
#> addition: None
#> removal: 'Adelie'
#> island:
#> addition: None
#> removal: 'Torgersen'
#> ==========================================================なお、初期設定では、データセットから除外された列が多い場合、テキストの視認性を維持するために列名の一部が省略されます。
mroz = wooldridge.data('mroz')
print(py4st.review_wrangling(
mroz, mroz.loc[:, 'inlf':'wage']
))
#> ================================ Review of wrangling =================================
#> The shape of DataFrame:
#> Rows: before 753 -> after 753 (No change)
#> Cols: before 22 -> after 7 (-15)
#>
#> Column additions and removals:
#> No columns were added.
#> removed: 'repwage', 'hushrs', 'husage', 'huseduc', 'huswage' and other 10 column(s)
#>
#> No existing columns had their type changed.
#>
#> No existing columns decreased the number of missing values.
#>
#> No columns had categories added or removed.
#> ======================================================================================デフォトのレビューには含まれませんが、items に 'numeric' を指定・追加することで、数値変数について ASCII 文字列の箱ひげ図による分布の要約を出力できます。
print(py4st.review_wrangling(before, after, items = 'numeric'))
#> =================== Review of wrangling ====================
#> Boxplot of Numeric values (for reference):
#> bill_length_mm
#> before: 32.10|------======:====-----------| 59.60
#> after: 40.90 |----==:===---------| 59.60
#> bill_depth_mm
#> before: 13.10|-------======:=====---------| 21.50
#> after: 13.10|----====:=======---------| 20.80
#> flipper_length_mm
#> before: 172.00|-------====:========--------| 231.00
#> after: 178.00 |----------======:====----| 230.00
#> body_mass_g
#> before: 2,700.00|-----====:======------------|6,300.00
#> after: 2,700.00|--------=======:====--------|6,300.00
#> year
#> before: 2,007.00|=============:==============|2,009.00
#> after: 2,007.00|=============:==============|2,009.00
#> ============================================================注意 Notes
本関数では、
beforeとafterが同一の DataFrame バックエンド(例:どちらも pandas、またはどちらも polars)であることを前提としています。異なるバックエンドを混在させた場合、エラーが発生します。review_wrangling()関数は、行(レコード)単位の差分(値の変更・削除など)を追跡していません。これは、レコード単位の差分を追跡するためには index が必要になり、特定のバックエンド(e.g. Pandas)への依存が生じることと、前処理では行の並び替えや index の再設定によって before と after のレコード対応付けが曖昧になりやすいことが理由です。そのため、本関数は個々のレコードの変化ではなく、データセット全体に生じた構造的な変化をレビューする関数として設計しています。
参考 See also
review_wrangling() 関数で出力される各項目を単独で提供する関数については、Individual review functions を参照してください。また、列のデータ型に基づいた比較については compare_df_cols() を、数値変数の統計値に基づいた比較については compare_df_stats() もご参照ください。
そのほか、review_wrangling() 関数の実践的な使い方については、vignette を参照してください。
