【Python 04】数据清洗:fillna()处理数据行中的缺失/异常值

来来来,咱们一起看一道题:
用最小代码量,从图片一提取数据变为图片二:
图片一
图片二
解题思路:

对比图片二与图片一目的是:使各个 INDEX 后面6列数据等于其不为空值(not nan)且不为"."的值。
那处理方式就大概就会有几种了,其中一种处理思路:
把不同的 INDEX 里的第一条中的"."和空值全部换成其下面的数据。
所以就会用到pandas里的 fillna() 或者 bfill() or ffill() 函数来处理。

引入相关的包
import numpy as np
import pandas as pd
读取数据表
df = pd.read_excel(r"C:\xxxx\xxxx\xxxx\test list.xlsx")
得到dataframe 数据集
图片三
处理方式拆解
# 一、REPLACE:用"np.NAN"替换掉".";
df=df.replace('.',np.NAN)
# 二、BFILL:向上填充;
df=df.bfill()
# 三、按INDEX 分组后取第一条数据;
df=df.groupby('INDEX').first()
一、用空值替换掉"."
二、用bfill向上填充
三、按INDEX 分组后取第一条数据

OK了,这样的话达到了我们预期目标啦~
我们来看看这题目所涉及的知识点 knowledge point 吧~

Knowledge Point 知识点:
fillna 函数

Pandas.DataFrame.fillna
Pandas 官方文档:
填充“空值”用的是这个特别的函数方式。
参数(因素)包括:
DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)

  • value: scalar, dict, Series, or DataFrame
    支持的数据类型:scalar(标量), dict, Series, or DataFrame
    Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list.
    value 是用于填充的空值的值。

  • method: {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None
    Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap.
    method参数:改变替代值的方式,当为’ffill’,表示用前面的值填充,当’bfill’表示用后面的值填充。

  • axis: {0 or ‘index’, 1 or ‘columns’}
    Axis along which to fill missing values.
    axis参数默认为0,即沿着行填充,为1则沿着列填充

  • inplace: bool, default False
    If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame).
    传入inplace参数:是否在原来的数据上操作,默认为False,表示重新拷贝了一份数据,然后在拷贝的数据上操作。

  • limit: int, default None
    If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.
    传入limit=” “限制填充个数

  • downcast: dict, default is None
    A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible).

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eason DayDayUp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值