LoginSignup
1
0

More than 1 year has passed since last update.

n個以上欠損値があるカラム(列)を削除

Last updated at Posted at 2022-12-19

概要

pandasのデータフレームで欠損値がn個以上あるカラム(列)を削除したい場合の方法。

データを用意

import numpy as np
import pandas as pd

data_path = "path/train.csv"
df = pd.read_csv(data_path)

方法1

dropna()を使う方法。
dropna()は欠損値ではない要素の数がn個以上ある列(行)を残し、それ以外の列(行)を削除する。
よって、欠損値がn個以上ある列を削除したい場合は、行数を取得して、(行数-n)をdropnaに渡してやれば良い。
以下は、n=5の場合。

n_samples = len(df)
n_thresh = n_samples - 5  # 行数 - n
df_null_rm = df.dropna(thresh=n_thresh, axis=1)

方法2

各列の欠損数を算出して、欠損数がn個より少ない列だけ抜き出す方法。
isnull()で欠損値か判定し、sum()で列ごとの欠損数を算出する。
各列の欠損数がn個より少ないかどうかを示すブール型のSeries(もしくはリスト)を算出し、locで抜き出す。
以下は、n=5の場合。

df_null_rm = df.loc[:, df.isnull().sum()<5]

もしくは、リストを使いたい場合は、

df_null_rm = df.loc[:, list(df.isnull().sum()<5)]
1
0
2

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
0