Inf 表示正无穷大或负无穷大,通常是在数学计算中产生的结果。
例如,
1 2 3 4 5 | import numpy as np # 创建一个包含 Infinity 的数组 arr = np.array([ 3.0 , 4.0 , np.inf, - np.inf]) print (arr) |
1)通过where方法和isinf方法查找Inf行和列
1 2 3 4 5 6 7 8 9 10 11 | import pandas as pd import numpy as np df = pd.DataFrame(np.arange( 18 ).reshape( 3 , 6 ), index = list ( 'abc' ), columns = list ( 'uvwxyz' )) print ( '*' * 36 ) # 将df的第一列变成Inf df.u = np.inf print (df) print ( '*' * 36 ) #输出结果,是一个tuple,前面array是横坐标,后面的array是纵坐标。 print (np.where(np.isinf(df))) |
2)数据处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import pandas as pd import numpy as np df = pd.DataFrame(np.arange( 18 ).reshape( 3 , 6 ), index = list ( 'abc' ), columns = list ( 'uvwxyz' )) print ( '*' * 36 ) # 将df的第一列变成NaN df.u = np.inf print (df) print ( '*' * 36 ) #输出结果,是一个tuple,前面array是横坐标,后面的array是纵坐标。 print (np.where(np.isinf(df))) print ( '*' * 36 ) # 使用 replace 替换整个 DataFrame 中的 Inf 值为特定值 print (df.replace(np.inf, 1 , inplace = False )) print ( '*' * 36 ) #使用np.isinf() df[np.isinf(df)] = 11.0 print (df) print ( '*' * 36 ) # 创建一个包含 Inf 的数组 arr = np.array([ 3.0 , 4.0 , np.inf, 6.0 ]) # 将Inf值为5 arr[np.isinf(arr)] = 5 print (arr) |
3)删除有Inf的行
1 2 3 4 5 6 7 8 9 10 11 12 | import pandas as pd import numpy as np x = np.arange( 0 , 30 ).reshape( 5 , 6 ) x = np.array(x,dtype = float ) x[ 2 , 3 ] = np.inf x[ 0 , 4 ] = np.inf print (x) print ( '*' * 36 ) #删除包含Inf的行 x1 = np.delete(x,np.where(np.isinf(x))[ 0 ],axis = 0 ) print (x1) |
注意:np.inf和np.nan的处理方法基本相同,注意调用处理时方法名。None是Python中用于标识空缺数据,Nan是nunpy和pandas中用于标识空缺数据,None是一个Python特殊的数据类型, 但是NaN却是用一个特殊的float。
在用DataFrame计算变化率时,例如(今天-昨天) / 昨天恰好为(2-0) / 0时,这些结果数据会变为inf。
为了方便后续处理,可以利用numpy,将这些inf值进行替换。
1. 将某1列(series格式)中的 inf 替换为数值。
1 2 3 | import numpy as np df[ 'Col' ][np.isinf(df[ 'Col' ])] = - 1 |
2. 将某1列(series格式)中的 inf 替换为NA值。
1 2 3 | import numpy as np df[ 'Col' ][np.isinf(df[ 'Col' ])] = np.nan |
3. 将整个DataFrame中的 inf 替换为数值(空值同理)。#感谢评论区的补充
1 2 3 4 5 6 | import numpy as np df.replace(np.inf, - 1 ) #替换正inf为-1 #替换正负inf为NA,加inplace参数 df.replace([np.inf, - np.inf], np.nan, inplace = True ) |