學習筆記226—Python Numpy之Nan和Inf處理


一、概念

Nan:Not a number

Inf:Infinity(無窮大)

當然容易搞混的還有None,None是python中用於標識空缺數據,Nan是nunpy和pandas中用於標識空缺數據,None是一個python特殊的數據類型, 但是NaN卻是用一個特殊的float,此處我僅針對Nan和Inf的處理。

二、Nan、Inf處理(以Nan為主,Inf可以借鑒相應方法)

1、找到Nan和Inf的行、列

其關鍵是通過where方法和isnan方法。

df = pd.DataFrame(np.arange(24).reshape(4,6), index=list('abcd'), columns=list('xyzuvw')) Output: x y z u v w a 0 1 2 3 4 5 b 6 7 8 9 10 11 c 12 13 14 15 16 17 d 18 19 20 21 22 23 # 將df的第一列變成NaN df.x = np.nan Output: x y z u v w a NaN 1 2 3 4 5 b NaN 7 8 9 10 11 c NaN 13 14 15 16 17 d NaN 19 20 21 22 23 np.where(np.isnan(df)) #得到結果,是一個tuple,前面array是橫坐標,后面的array是縱坐標。 Output: (array([0, 1, 2, 3], dtype=int64), array([0, 0, 0, 0], dtype=int64)) 

2、數據處理

(1)數據替換

關鍵還是isnan方法,得到Nan值的索引。

df=df[np.isnan(df)]=2
#所得結果如下
Output:
     x   y   z   u   v   w
a  2.0   1   2   3   4   5
b  2.0   7   8   9  10  11
c  2.0  13  14  15  16  17
d  2.0  19  20  21  22  23

(2)刪除相關數據

如果Nan所在數據行或列不影響整體數據分析,可以考慮去除相應行和列。

主要思路是通過isnan函數獲得nan所在索引,通過where函數將其轉成tuple形式,,再通過delete函數將所在行刪除。

#create testing data
x=np.arange(0,24).reshape(4,6)
x=np.array(x,dtype=float)
x[2,3]=np.nan
x[0,4]=np.nan
print(x)
Output:
[[ 0.  1.  2.  3. nan  5.]
 [ 6.  7.  8.  9. 10. 11.]
 [12. 13. 14. nan 16. 17.]
 [18. 19. 20. 21. 22. 23.]]

#delete rows which have nan 
x1=np.delete(x,np.where(np.isnan(x))[0],axis=0))
print(x1)
Output:
[[ 6.  7.  8.  9. 10. 11.]
 [18. 19. 20. 21. 22. 23.]]

參考鏈接:https://zhuanlan.zhihu.com/p/38712765

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM