缺失值和異常值處理

一、缺失值

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.pswp.cn/news/391660.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391660.shtml
英文地址,請注明出處:http://en.pswp.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&#…