如何在 Pandas DataFrame 的列中用零替换 NaN 值?
要在 Pandas DataFrame 的列中用零或其他值替换 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
以上是 如何在 Pandas DataFrame 的列中用零替换 NaN 值? 的全部内容, 来源链接: utcz.com/z/359890.html