如何在 Pandas DataFrame 的列中用零替换 NaN 值?
要在PandasDataFrame的列中用零或其他值替换NaN值,我们可以使用方法。df.fillna()
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧df。
使用df.fillna(0)将DataFrame中的NaN替换为值0。
同样使用df.fillna(5)和df.fillna(7)分别用5和7替换DataFrame中的NaN。
打印替换的NaN,DataFrame。
示例
import pandas as pd import numpy as np df = pd.DataFrame( { "x": [5, np.nan, 1, np.nan], "y": [np.nan, 1, np.nan, 10], "z": [np.nan, 1, np.nan, np.nan] } ) print "Input series is:\n", df print "After replacing NaN with 0:\n", df.fillna(0) print "After replacing NaN with 5:\n", df.fillna(5) print "After replacing NaN with 7:\n", df.fillna(7)输出结果
Input series is: x y z 0 5.0 NaN NaN 1 NaN 1.0 1.0 2 1.0 NaN NaN 3 NaN 10.0 NaN After replacing NaN with 0: x y z 0 5.0 0.0 0.0 1 0.0 1.0 1.0 2 1.0 0.0 0.0 3 0.0 10.0 0.0 After replacing NaN with 5: x y z 0 5.0 5.0 5.0 1 5.0 1.0 1.0 2 1.0 5.0 5.0 3 5.0 10.0 5.0 After replacing NaN with 7: x y z 0 5.0 7.0 7.0 1 7.0 1.0 1.0 2 1.0 7.0 7.0 3 7.0 10.0 7.0