# 如何在 Pandas DataFrame 的列中將所有 NaN 值替換為零

Ahmed Waheed 2023年1月30日 2020年6月9日

``````import pandas as pd
import numpy as np
data = {'name': ['Oliver', 'Harry', 'George', 'Noah'],
'percentage': [90, 99, 50, 65],
df = pd.DataFrame(data)
print(df)
``````

``````     name  percentage  grade
0  Oliver          90   88.0
1   Harry          99    NaN
2  George          50   95.0
3    Noah          65    NaN
``````

## `df.fillna()` 方法將所有 NaN 值替換為零

``````import pandas as pd
import numpy as np
data = {'name': ['Oliver', 'Harry', 'George', 'Noah'],
'percentage': [90, 99, 50, 65],
df = pd.DataFrame(data)
df = df.fillna(0)
print(df)
``````

``````     name  percentage  grade
0  Oliver          90   88.0
1   Harry          99    0.0
2  George          50   95.0
3    Noah          65    0.0
``````

`df.fillna()` 方法用給定值填充 NaN 值。它不會更改物件資料，但預設情況下會返回一個新的 DataFrame，除非將 `inplace` 引數設定為 True。

``````import pandas as pd
import numpy as np
data = {'name': ['Oliver', 'Harry', 'George', 'Noah'],
'percentage': [90, 99, 50, 65],
df = pd.DataFrame(data)
df.fillna(0, inplace=True)
print(df)
``````

## `df.replace()` 方法

``````    import pandas as pd
import numpy as np
data = {'name': ['Oliver', 'Harry', 'George', 'Noah'],
'percentage': [90, 99, 50, 65],
df = pd.DataFrame(data)
nan_replaced = df.replace(np.nan,0)
print(nan_replaced)
``````

``````     name  percentage  grade
0  Oliver          90   88.0
1   Harry          99    0.0
2  George          50   95.0
3    Noah          65    0.0
``````