Python Pandas - 用常量值填充缺失的列值 (NaN)
使用该fillna()方法并使用参数value在其中为所有缺失值设置一个常量值。首先,让我们使用各自的别名导入所需的库-
import pandas as pd import numpy as np
创建一个包含2列的DataFrame。我们已经使用Numpynp.NaN设置了NaN值-
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN] } )
使用NaN为列值放置一个常量值,即此处的Units列-
constVal = 200
将NaN替换为常量值,即200-
dataFrame['Units'].fillna(value=constVal, inplace=True)
示例
以下是代码-
import pandas as pd import numpy as np #CreateDataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN] } ) print"DataFrame ...\n",dataFrame #placingaconstantvalueforthecolumnvalueswithNaNi.e,forUnitscolumnshere constVal = 200 #ReplaceNaNswiththeconstantvaluei.e200 dataFrame['Units'].fillna(value=constVal, inplace=True) print"\nUpdated Dataframe after filling NaN values with constant values...\n",dataFrame输出结果
这将产生以下输出-
DataFrame ... Car Units 0 BMW 100.0 1 Lexus 150.0 2 Lexus NaN 3 Mustang 80.0 4 Bentley NaN 5 Mustang NaN Updated Dataframe after filling NaN values with constant values... Car Units 0 BMW 100.0 1 Lexus 150.0 2 Lexus 200.0 3 Mustang 80.0 4 Bentley 200.0 5 Mustang 200.0