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 tkinter组件使用详解

python tkinter组件使用详解

这篇文章主要介绍了python tkinter组件使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.按钮 # 按钮 #...

Python使用smtplib模块发送电子邮件的流程详解

Python使用smtplib模块发送电子邮件的流程详解

1、登录SMTP服务器 首先使用网上的方法(这里使用163邮箱,smtp.163.com是smtp服务器地址,25为端口号): import smtplib server = smt...

python设定并获取socket超时时间的方法

python写法 import socket def test_socket_timeout(): s = socket.socket(socket.AF_INET,...

pandas使用get_dummies进行one-hot编码的方法

pandas使用get_dummies进行one-hot编码的方法

离散特征的编码分为两种情况: 1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码 2、离散特征的取值有大小的意义,比如size:[X...

Python环境下搭建属于自己的pip源的教程

一、安装pip2pi工具: pip install pip2pi 或: git clone https://github.com/wolever/pip2pi cd pip2...