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设计】。

相关文章

Python3中的2to3转换工具使用示例

python3与python2的还是有诸多的不同,比如说在2中: 复制代码 代码如下: print "Hello,World!"  raw_input()  在...

Python tensorflow实现mnist手写数字识别示例【非卷积与卷积实现】

本文实例讲述了Python tensorflow实现mnist手写数字识别。分享给大家供大家参考,具体如下: 非卷积实现 import tensorflow as tf from t...

python3正则提取字符串里的中文实例

python3正则提取字符串里的中文实例

如下所示: # -*- coding: utf-8 -*- import re #过滤掉除了中文以外的字符 str = "hello,world!!%[545]你好234世界。。。"...

django 快速启动数据库客户端程序的方法示例

django 快速启动数据库客户端程序的方法示例

实际工作经历中,免不了有时候需要连接数据库进行问题排查分析的场景,之前一直习惯通过 mysql -uxxx -hxxxx -P1234 ... 这样的方式来启动命令行形式的 MySQL...

Python实现自动添加脚本头信息的示例代码

前言 每个人写脚本时的格式都会有所不同,有的会注明脚本本身的一些信息,有的则开门见山,这在小团队里其实没什么,基本别人做什么你也都知道,但如果放到大的团队就比较麻烦了,因为随着人数的增多...