LoginSignup
2
3

More than 5 years have passed since last update.

[Python][Pandas]データフレーム中の欠損値を平均値で補完する

Last updated at Posted at 2019-01-30

scikit-learnのImputerクラスの使い方について、毎回細かい部分を忘れるので備忘のため掲載。

from sklearn.preprocessing import Imputer
import numpy as np
import pandas as pd

# 対象データフレームから数値型のカラム名のみ取得
list_num_columns = df.select_dtypes(include='number').columns
list_except_num_columns = df.select_dtypes(exclude='number').columns

# 行ごと(axix=0)の平均値(atrategy='mean')を計算する
imr = Imputer(missing_values='NaN', strategy='mean', axis=0)
imr = imr.fit(df[list_num_columns].values)
impyted_data = imr.transform(df.drop([list_except_num_columns ], axis=1)

# 数値型とそれ以外のデータフレームを作成する
df_only_num = pd.DataFrame(impyted_data.values, index=df.index ,columns=list_num_columns)
df_except_num = df[list_except_num_columns]

# 作成した各データフレームを結合
df = pd.merge(df_except_num, df_only_num, right_index=True, left_index=True)
2
3
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
2
3