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

yipeiwu_com5年前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如何拆分含有多种分隔符的字符串

案例:        把某个字符串依据分隔符拆分,该字符包含不同的多种分隔符,如下    &nb...

Python Paramiko模块的安装与使用详解

一、前言 常见的解决方法都会需要对远程服务器必要的配置,如果远程服务器只有一两台还好说,如果有N台,还需要逐台进行配置,或者需要使用代码进行以上操作时,上面的办法就不太方便了。而使用pa...

解决Django的request.POST获取不到内容的问题

我通过如下的一段程序发送post请求: import urllib3 pool = urllib3.connection_from_url('http://127.0.0.1:809...

实例讲解Python中浮点型的基本内容

1.浮点数的介绍 float(浮点型)是Python基本数据类型中的一种,Python的浮点数类似数学中的小数和C语言中的double类型; 2.浮点型的运算 浮点数和整数在计算机内部存...

浅谈python之高阶函数和匿名函数

map() map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。 def func(x)...