大 pandas 类别缺失值的插补 [英] Imputation of missing values for categories in pandas

查看:59
本文介绍了大 pandas 类别缺失值的插补的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是如何为 Pandas 数据框中的类别列填充最频繁级别的 NaN?

The question is how to fill NaNs with most frequent levels for category column in pandas dataframe?

在 R randomForest 包中有na.roughfix 选项:<代码>一个完整的数据矩阵或数据框.对于数值变量,NA 被替换为列中位数.对于因子变量,NA 被替换为最频繁的水平(随机打破关系).如果对象不包含 NA,则返回原样.

In R randomForest package there is na.roughfix option : A completed data matrix or data frame. For numeric variables, NAs are replaced with column medians. For factor variables, NAs are replaced with the most frequent levels (breaking ties at random). If object contains no NAs, it is returned unaltered.

在 Pandas 的数值变量中,我可以用 :

in Pandas for numeric variables I can fill NaN values with :

df = df.fillna(df.median())

推荐答案

您可以使用 df = df.fillna(df['Label'].value_counts().index[0]) 来用一列中最频繁的值填充 NaN.

You can use df = df.fillna(df['Label'].value_counts().index[0]) to fill NaNs with the most frequent value from one column.

如果你想用自己最频繁的值填充每一列,你可以使用

If you want to fill every column with its own most frequent value you can use

df = df.apply(lambda x:x.fillna(x.value_counts().index[0]))

更新 2018-25-10

0.13.1 开始,pandas 包含用于 系列数据帧.您可以像这样使用它来填充每列的缺失值(使用它自己最频繁的值)

Starting from 0.13.1 pandas includes mode method for Series and Dataframes. You can use it to fill missing values for each column (using its own most frequent value) like this

df = df.fillna(df.mode().iloc[0])

这篇关于大 pandas 类别缺失值的插补的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆