【備忘録】pandas.Series の mask は True の要素に where は False の要素にアクセスする

はじめに

表形式のデータを pandas で処理しているとよく(毎回?)maskwhere の使い分け方を迷うので、未来の自分のために備忘録を書いておきます1

pandas.Series の mask と where

pandas.Series.maskpandas.Series.where はどちらも pandas.Series のメソッドで、同じ引数を受け取ります。

maskcond が True の行のみ s の要素を others の対応する要素で置換します。where はその逆で cond が False の行のみ s の要素を others の対応する要素で置換します

import pandas as pd

s = pd.Series([1, 2, 3, 4, 5])  # length = 5
othres = pd.Series([-1, -2, -3, -4, -5])  # length = 5
cond = pd.Series([False, True, True, False, True])  # bool array, length = 5

s.mask(cond, others)  # `cond` が True だと置換
s.where(cond, others)  # `cond` が Falase だと置換

上のコードだと mask, where の返す Series は次の表の通りになります。

s others cond mask where
1 -1 False 1 -1
2 -2 True -2 2
3 -3 True -3 3
4 -4 False 4 -4
5 -5 True -5 5

その他

maskwhere も引数 inplace を True にしない限り元の Series を上書きしません。inplace はデフォルトでは False です。

othersスカラーを指定すると勝手にブロードキャストしてくれます。others はデフォルトでは numpy.nan, pd.NA 等の元のデータ型に対応した欠損値になります。


  1. 未来の自分がこの備忘録の存在を忘れている可能性は考えないことにした