LoginSignup
5
4

More than 5 years have passed since last update.

DataFrame各列の欠損率を集計する

Posted at

要約

  • df.isnull().sum() / len(df)で出来ます。

動機

  • DataFrame内の多数の列に対して、ありにも欠損が多い列を列ごとdropしたい。
  • その前に、そもそも各列がどのくらい欠損してるのか調べたい。

やり方

準備

import numpy
import pandas

欠損があるDataFrameを作る

こんな感じで欠損があるDataFrameを作る。

dataset.head()

JupyterLab.png

欠損の数をカウントする

pythonのbool型は1と0みたいな振る舞いをする(;´Д`)

True + True + True  #=> 3
False + False + False  #=> 0

numpyもそんな感じ。

numpy.array([True, True, True]).sum()  #=> 3

なのでisnull()が返してくるboolsum()する事で各列の欠損数がカウント出来る。

dataset.isnull().sum()
output
0     8
1     9
2    15
3     5
4    13
5     8
6     8
7    10
8     5
9    11
dtype: int64

※0〜9は列名で、それぞれの欠損数がカウントされています。

欠損率を計算する

欠損数をDataFrameの行数で割れば、欠損率になる。

dataset.isnull().sum() / len(dataset)
output
0    0.08
1    0.09
2    0.15
3    0.05
4    0.13
5    0.08
6    0.08
7    0.10
8    0.05
9    0.11
dtype: float64

見やすくする

DataFrameにまとめて欠損率順にsortすると見やすい。

null_count = dataset.isnull().sum()
null_rate = null_count / len(dataset)

null_table = pandas.DataFrame({
    'null_couunt': null_count,
    'null_rate': null_rate
})

null_table.sort_values(by='null_rate', ascending=False)

JupyterLab.png

この場合、indexがカラム名です。

5
4
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
5
4