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.]]