- はじめに
- 解決方法
- loc で代入
- numpy.where を使う
- まとめ
はじめに
Pandas で 3 項演算子のような処理を行いたい事がままあるのですが、簡単に行う方法を記載します
解決方法
以下のようなデータを持っている DataFrame を考えます
df = pd.DataFrame({'A': [1, 0, 1],
'B': ['B1', 'B2', 'B3'],
'C': ['C1', 'C2', 'C3']})ここで、カラム A が 1 以上であれば カラム C をカラム B の値に置換したいとします
普通の python 的な 3 項演算子で記述しようとすると以下のようになりますが、これは実行できません
df['C'] = df['B'] if df['A'] >= 1 else df['C']loc で代入
loc にて boolean Series と label を指定すると、boolean Series で True となってい行を取得出来る
pandas.DataFrame.loc - pandas 1.3.2 documentation
Access a group of rows and columns by label(s) or a boolean array. is primarily label based, but may also be used with a boolean array. Allowed inputs are: A single label, e.g. or , (note that is interpreted as a label of the index, and never as an integer position along the index).
pandas.pydata.org
以下のようにすると、 A 列が 1 以上 の行の C 列を Series として取得できます
>>> df.loc[df['A'] >= 1, 'C']
0 C1
2 C3
Name: C, dtype: object
# ちなみに、配列を渡すと DataFrame として取得できます
>>> df.loc[df['A'] >= 1, ['C']]この性質を利用すると、Pandas の場合は以下のようなコードで上記の 3 項演算子と同じような処理が実現可能です
df.loc[df['A'] >= 1, 'C'] = df['B']これは条件を満たす行の C 列を取得し、そこに値を代入すという事をしています
numpy.where を使う
同様の処理を numpy の where を使って実現する事もできます
numpy.where - NumPy v1.21 Manual
C-Types Foreign Function Interface ( numpy.ctypeslib )
numpy.org
以下は、条件に応じて定数を代入する例です
df['D'] = np.where(df['A'] >= 1, True, False)以下のように Series の値を代入する事もできます
df['D'] = np.where(df['A'] >= 1, df['B'], df['C'])まとめ
Pandas で 3 項演算子 like な処理を行う際の Tips を記載しました