0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

欠損値の対処方法まとめ

Last updated at Posted at 2025-05-27

■はじめに

Excelではハンドリングしきれないボリュームのデータをいじる際、NaN/nullの処理を正しく理解してキッチリ前処理しておかないと大惨事を起こし切腹不可避となる。分母とする列がNaNまみれだったりとか、DataFrameどうしをマージする時とか。
自分用の備忘録として、Python、pandasでの使用頻度が高い対処方法をまとめておく。

■df.dropna()

みんな大好きなやつ。
NaN/nullデータがいるrowを消す。

df.dropna(axis=1)  # NaNを含む列を削除
df.dropna(subset=['col1', 'col2'])  # 特定の列にNAがある行だけ削除

■df.fillna(value)

NaN/nullデータに値(0)とかを代入する。

■ skipna=

skipna=False

# 例

df['new_col'] = df[['x', 'y']].min(axis=1, skipna=False)

やっていること:
・dfから'x', 'y'の二列を取り出す。
・axis=1:行方向に最小値を計算する(各行で 'x' と 'y' のどちらが小さいかを比較)
・skipna=False:NaNがある場合は無視せず、NaNを含む行の結果もNaNにする
・最小値の計算結果をdf の 'new_col' という新しい列に代入する

[5.0, NaN, NaN]

みたいになる。

skipna = True

# 例

df['new_col'] = df[['x', 'y']].min(axis=1, skipna=True)

sikipna部分だけ置き換えると、こんな感じの出力になる。

[5.0, 20.0, 30.0]

■ isna() / notna()

特定のセルがNAかどうかを判定するやつ。

df[df['col'].isna()]      # 'col' がNAの行を抽出
df[df['col'].notna()]     # 'col' がNAでない行を抽出

■ combine_first()

2つのDataFrameを比較して、NAを埋める。

df['col'] = df['col1'].combine_first(df['col2'])
# col1がNAならcol2の値で埋める

■ where() / mask()

私はほぼやらないけど、条件に応じてNAを代入したいとき。

df['col'] = df['col'].where(df['col'] > 0)  # 0以下の値をNAにする
df['col'] = df['col'].mask(df['col'] <= 0)  # 同じ

■感想

メーカーや工場だけでなく、データ加工屋もヒヤリハット、KY(危険予知)等やるべきだと思う。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?