pandas 使用均值填充缺失值列的小技巧分享

yipeiwu_com6年前Python基础

pd.DataFrame中通常含有许多特征,有时候需要对每个含有缺失值的列,都用均值进行填充,代码实现可以这样:

for column in list(df.columns[df.isnull().sum() > 0]):
  mean_val = df[column].mean()
  df[column].fillna(mean_val, inplace=True)

# -------代码分解-------
# 判断哪些列有缺失值,得到series对象
df.isnull().sum() > 0
# output
contributors           True
coordinates            True
created_at            False
display_text_range        False
entities             False
extended_entities         True
favorite_count          False
favorited            False
full_text            False
geo                True
id                False
id_str              False
...

# 根据上一步结果,筛选需要填充的列
df.columns[df.isnull().sum() > 0]
# output
Index(['contributors', 'coordinates', 'extended_entities', 'geo',
    'in_reply_to_screen_name', 'in_reply_to_status_id',
    'in_reply_to_status_id_str', 'in_reply_to_user_id',
    'in_reply_to_user_id_str', 'place', 'possibly_sensitive',
    'possibly_sensitive_appealable', 'quoted_status', 'quoted_status_id',
    'quoted_status_id_str', 'retweeted_status'],
   dtype='object')

以上这篇pandas 使用均值填充缺失值列的小技巧分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python里使用正则的findall函数的实例详解

python里使用正则的findall函数的实例详解 在前面学习了正则的search()函数,这个函数可以找到一个匹配的字符串返回,但是想找到所有匹配的字符串返回,怎么办呢?其实得使用f...

elasticsearch python 查询的两种方法

elasticsearch python 查询的两种方法

elasticsearch python 查询的两种方法,具体内容如下所述: from elasticsearch import Elasticsearch es = Elastic...

对python中for、if、while的区别与比较方法

如下所示: if应用举例: #if 若条件成立,只执行一次 #if 条件:如果条件成立,执行条件后的代码块内容,不成立,直接跳过代码块 #判断如果年龄age小于18,输出未成年 #=...

Pytorch修改ResNet模型全连接层进行直接训练实例

之前在用预训练的ResNet的模型进行迁移训练时,是固定除最后一层的前面层权重,然后把全连接层输出改为自己需要的数目,进行最后一层的训练,那么现在假如想要只是把 最后一层的输出改一下,不...

Python3解释器知识点总结

Python3解释器知识点总结

Python3 解释器 Linux/Unix的系统上,一般默认的 python 版本为 2.x,我们可以将 python3.x 安装在 /usr/local/python3 目录中。...