要在 Pandas 系列的列中用零或其他值替换 NaN 值,我们可以使用方法。s.fillna()
创建一个带有轴标签(包括时间序列)的一维ndarray。
打印输入系列。
使用s.fillna(0)将系列中的 NaN 替换为值 0。
类似地,使用s.fillna(5)和s.fillna(7)分别用值 5 和 7 替换串联的 NaN。
打印替换的 NaN 系列。
import pandas as pd import numpy as np s = pd.Series([1, np.nan, 3, np.nan, 3, np.nan, 7, np.nan, 3]) print "Input series is:\n", s print "After replacing NaN with 0:\n", s.fillna(0) print "After replacing NaN with 5:\n", s.fillna(5) print "After replacing NaN with 7:\n", s.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