缺失值和异常值处理

一、缺失值

1.空值判断

isnull()空值为True,非空值为False

notnull() 空值为False,非空值为True

s = pd.Series([1,2,'3',np.nan,'hello',np.nan])
df = pd.DataFrame({'a':[1,2,np.nan,'3'],'b':[2,np.nan,'3','hello']})
print(s.isnull())
print(s[s.isnull() == False])  #求s中的非空值,或者直接s[s.notnull()]print(df.notnull())
print(df[df['b'].notnull()])  #求s中的非空值,或者df[df.isnull() == False]
0    False
1    False
2    False
3     True
4    False
5     True
dtype: bool
0        1
1        2
2        3
4    hello
dtype: objecta      b
0   True   True
1   True  False
2  False   True
3   True   Truea      b
0    1      2
2  NaN      3
3    3  hello
结果

 

2.空值删除

dropna()删除所有出现空值的行,即任何一个字段出现空值该行都会被删除。

dropna()默认返回删除空值后的数据且不修改原数据,加参数inplace=True直接修改原数据

s = pd.Series([1,2,'3',np.nan,'hello',np.nan])
df = pd.DataFrame({'a':[1,2,np.nan,'3'],'b':[2,np.nan,'3','hello']})
print(s.dropna())
df.dropna(inplace = True)
print(df)
0        1
1        2
2        3
4    hello
dtype: objecta      b
0  1      2
3  3  hello
结果

 

3.空值填充

fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)
value 指定value填充空值,默认为None
method 填充方法,backfill/bfill使用后面的值填充,pad/ffill使用前面的值填充,默认为None
inplace 默认为False不修改原数据
limit 如果有多个空值,最多修改多少个

s = pd.Series([1,2,'3',np.nan,'hello',np.nan])
df = pd.DataFrame({'a':[1,2,np.nan,'3'],'b':[2,np.nan,'3','hello']})
print(s.fillna(0))
print(s.fillna(0,limit = 1))
print(df.fillna(method = 'bfill'))
0        1
1        2
2        3
3        0
4    hello
5        0
dtype: object
0        1
1        2
2        3
3        0
4    hello
5      NaN
dtype: objecta      b
0  1      2
1  2      3
2  3      3
3  3  hello
In [41]:
结果

 

4.空值替换

replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
to_replace 被替换值
value 替换值
method 如果不指定value,使用method指定的方法进行替换,pad/ffill使用前面的值替换,backfill/bfill使用后面的值替换
limit 如果被替换的值有多个,最多替换多少个

s = pd.Series([1,2,'3',np.nan,'hello',np.nan])
print(s.replace(np.nan,method = 'bfill'))
0        1
1        2
2        3
3    hello
4    hello
5      NaN
dtype: object
结果

 

5.缺失值处理方法

①直接删除空值(根据实际意义,如果缺失值占比<2%且不好填充,可考虑直接删除)

②使用均值/中位数/众数填充

③使用前值/后值填充

④插值,拉格朗日插值法

from scipy.interpolate import lagrange
x = [3,6,9]
y = [10,8,4]
print(lagrange(x,y),type(lagrange(x,y)))
print(lagrange(x,y)(15))
df = pd.DataFrame({'x':np.arange(20)})
df['y'] = lagrange(x,y)(df['x'])
plt.plot(df['x'],df['y'],linestyle='--',marker = 'o')
# -0.1111 x^2 + 0.3333 x + 10 <class 'numpy.poly1d'>
# -10.000000000000004

 

s = pd.Series(np.random.rand(100)*100)
s[3,6,33,56,45,66,67,80,90] = np.nan
print('数据个数为%d'%len(s))
s_na = s[s.isnull()]
print('缺失值个数为%d'%len(s_na))
print('缺失值占比%.2f%%'%(100*len(s_na)/len(s)))s_handle = s.fillna(s.median())
fig,axes = plt.subplots(1,4,figsize = (20,4))
s.plot.box(ax = axes[0],title = '数据分布')
s.plot(kind = 'kde',linestyle = '--',ax = axes[1],title = '折线图(默认删除缺失值)')
s_handle.plot(kind = 'kde',linestyle = '--',ax = axes[2],title = '折线图(中位数填充缺失值)')def f(data,n,k = 5):y = data[list(range(n-k,n+1+k))]y = y[y.notnull()]return lagrange(y.index,list(y))(n)for i in range(len(s)):if s.isnull()[i]: s[i] = f(s,i)print(i,f(s,i))

 

二、异常值

异常值是指样本中的个别值明显偏离其余的样本值,异常值也称离群点,异常值的分析也称为离群点的分析。

1.异常值鉴定  

①3α原则

对于服从正态分布的样本数据,通常认为 |样本值-均值| >3倍标准差的样本值为异常值。在实际工作中可自根据实际情况自定义这个倍数。

s = pd.Series(np.random.randn(1000)*100)
u = s.mean()
std = s.std()
print('样本均值为%.2f,标准差为%.2f'%(u,std))
p = stats.kstest(s,'norm',(u,std)).pvalue
if p > 0.05:print('样本服从正态分布')fig = plt.figure(figsize = (20,6))
ax1 = fig.add_subplot(1,2,1)
s.plot(kind = 'kde',linestyle ='--',title = '原始数据密度曲线')
plt.axvline(u+3*std,linestyle ='--',color = 'red')  #u+3*std处绘制垂直线
plt.axvline(u-3*std,linestyle ='--',color = 'red')  #u-3*std处绘制垂直线
unusual = s[abs(s-u) > 3*std] #异常值 
s_clean = s[abs(s-u) <= 3*std] #非异常值 
print('共有%d个异常值'%len(unusual)) 
ax2 = fig.add_subplot(1,2,2) plt.scatter(s_clean.index,s_clean.values,color = 'b') #非异常值用蓝色表示 
plt.scatter(unusual.index,unusual.values,color = 'r') #异常值用红色表示 
plt.title('正常值与异常值散点图') 
# 样本均值为-2.56,标准差为99.70 
# 样本服从正态分布 
# 共有5个异常值

②箱型图分析

箱型图中,是将样本值 > (q3+1.5*iqr)和样本值<(q1-1.5*iqr)的样本作为异常值。

s = pd.Series(np.random.randn(1000)*100)fig = plt.figure(figsize = (20,6))
ax1 = fig.add_subplot(121)
s.plot.box(vert = False,label = '样本数据箱型图')des = s.describe()
q1 = des['25%']
q3 = des['75%']
iqr = q3 - q1
ma = q3 + 1.5*iqr
mi = q1 - 1.5*iqr
unusual = s[(s>ma)|(s<mi)]
s_clean = s[(s<ma)&(s>mi)]
print('共有异常值%d个'%len(unusual))ax2 = fig.add_subplot(1,2,2)
plt.scatter(s_clean.index,s_clean.values,color = 'b')  #非异常值用蓝色表示
plt.scatter(unusual.index,unusual.values,color = 'r')  #异常值用红色表示
plt.title('正常值与异常值散点图')

 

2.异常值处理 

 删除,或类似空值填充的方法修补。

 

转载于:https://www.cnblogs.com/Forever77/p/11368091.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391660.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode 503. 下一个更大元素 II(单调栈)

给定一个循环数组&#xff08;最后一个元素的下一个元素是数组的第一个元素&#xff09;&#xff0c;输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序&#xff0c;这个数字之后的第一个比它更大的数&#xff0c;这意味着你应该循环地搜索它的下一个更…

setNeedsDisplay看我就懂!

前言&#xff1a; setNeedsDisplay异步执行的。它会自动调用drawRect方法&#xff0c;这样可以拿到 UIGraphicsGetCurrentContext&#xff0c;就可以绘制了。而setNeedsLayout会默认调用layoutSubViews&#xff0c;处理子视图中的一些数据。 一、着手 我定义了一个UIView的子类…

如何使用ArchUnit测试Java项目的体系结构

by Emre Savcı由EmreSavcı 如何使用ArchUnit测试Java项目的体系结构 (How to test your Java project’s architecture with ArchUnit) In this post, I will show you an interesting library called ArchUnit that I met recently. It does not test your code flow or bu…

解决ionic3 android 运行出现Application Error - The connection to the server was unsuccessful

在真机上启动ionic3打包成的android APK,启动了很久结果弹出这个问题&#xff1a; Application Error - The connection to the server was unsuccessful 可能是我项目资源太多东西了&#xff0c;启动的时间太久了&#xff0c;导致超时了。 解决方案是在项目目录下的config.xml…

特征工程之特征选择_特征工程与特征选择

特征工程之特征选择&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a; 这里没有神奇的配方或圣杯&#xff0c;尽管新世界可…

搭建Harbor企业级docker仓库

https://www.cnblogs.com/pangguoping/p/7650014.html 转载于:https://www.cnblogs.com/gcgc/p/11377461.html

leetcode 131. 分割回文串(dp+回溯)

给你一个字符串 s&#xff0c;请你将 s 分割成一些子串&#xff0c;使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 是正着读和反着读都一样的字符串。 示例 1&#xff1a; 输入&#xff1a;s “aab” 输出&#xff1a;[[“a”,“a”,“b”],[“aa”,“b”]]…

[翻译练习] 对视图控制器压入导航栈进行测试

译自&#xff1a;swiftandpainless.com/testing-pus… 上个月我写的关于使用 Swift 进行测试驱动开发的书终于出版了&#xff0c;我会在本文和接下来的一些博文中介绍这本书撰写过程中的一些心得和体会。 在本文中&#xff0c;我将会展示一种很好的用来测试一个视图控制器是否因…

python多人游戏服务器_Python在线多人游戏开发教程

python多人游戏服务器This Python online game tutorial from Tech with Tim will show you how to code a scaleable multiplayer game with python using sockets/networking and pygame. You will learn how to deploy your game so that people anywhere around the world …

版本号控制-GitHub

前面几篇文章。我们介绍了Git的基本使用方法及Gitserver的搭建。本篇文章来学习一下怎样使用GitHub。GitHub是开源的代码库以及版本号控制库&#xff0c;是眼下使用网络上使用最为广泛的服务&#xff0c;GitHub能够托管各种Git库。首先我们须要注冊一个GitHub账号&#xff0c;打…

leetcode132. 分割回文串 II(dp)

给你一个字符串 s&#xff0c;请你将 s 分割成一些子串&#xff0c;使每个子串都是回文。 返回符合要求的 最少分割次数 。 示例 1&#xff1a; 输入&#xff1a;s “aab” 输出&#xff1a;1 解释&#xff1a;只需一次分割就可将 s 分割成 [“aa”,“b”] 这样两个回文子串…

数据标准化和离散化

在某些比较和评价的指标处理中经常需要去除数据的单位限制&#xff0c;将其转化为无量纲的纯数值&#xff0c;便于不同单位或量级的指标能够进行比较和加权。因此需要通过一定的方法进行数据标准化&#xff0c;将数据按比例缩放&#xff0c;使之落入一个小的特定区间。 一、标准…

熊猫tv新功能介绍_熊猫简单介绍

熊猫tv新功能介绍Out of all technologies that is introduced in Data Analysis, Pandas is one of the most popular and widely used library.在Data Analysis引入的所有技术中&#xff0c;P andas是最受欢迎和使用最广泛的库之一。 So what are we going to cover :那么我…

关于sublime-text-2的Package Control组件安装方法,自动和手动

之前在自己的文章《Linux下安装以及破解sublim-text-2编辑器》的文章中提到过关于sublime-text-2的Package Control组件安装方法。 当时使用的是粘贴代码&#xff1a; 1import urllib2,os;pfPackage Control.sublime-package;ippsublime.installed_packages_path();os.makedirs…

上海区块链会议演讲ppt_进行第一次会议演讲的完整指南

上海区块链会议演讲pptConferences can be stressful even if you are not giving a talk. On the other hand, speaking can really boost your career, help you network, allow you to travel for (almost) free, and give back to others at the same time.即使您不讲话…

windows下Call to undefined function curl_init() error问题

本地项目中使用到curl_init()时出现Call to undefined function curl_init()的错误&#xff0c;去掉php.ini中的extensionphp_curl.dll前的分号还是不行&#xff0c;phpinfo()中无curl模块&#xff0c;于是上网搜索并实践了如下方法&#xff0c;成功&#xff1a; 在使用php5的c…

数据转换软件_数据转换

数据转换软件&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a;这里没有神奇的配方或圣杯&#xff0c;尽管新世界可能为您…

leetcode 1047. 删除字符串中的所有相邻重复项(栈)

给出由小写字母组成的字符串 S&#xff0c;重复项删除操作会选择两个相邻且相同的字母&#xff0c;并删除它们。 在 S 上反复执行重复项删除操作&#xff0c;直到无法继续删除。 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 示例&#xff1a; 输入&#x…

spring boot: spring Aware的目的是为了让Bean获得Spring容器的服务

Spring Aware的目的是为了让Bean获得Spring容器的服务 //获取容器中的bean名称import org.springframework.beans.factory.BeanNameAware;//获得资源加载器&#xff0c;可以获得额外的资源import org.springframework.context.ResourceLoaderAware; package ch2.aware; import …

10张图带你深入理解Docker容器和镜像

【编者的话】本文用图文并茂的方式介绍了容器、镜像的区别和Docker每个命令后面的技术细节&#xff0c;能够很好的帮助读者深入理解Docker。这篇文章希望能够帮助读者深入理解Docker的命令&#xff0c;还有容器&#xff08;container&#xff09;和镜像&#xff08;image&#…