如何使用 pandas fillna() 替换 nan 值
您可以使用fillna()函数来替换 pandas DataFrame 中的 NaN 值。
该函数使用以下基本语法:
#replace NaN values in one column df[' col1 '] = df[' col1 ']. fillna (0) #replace NaN values in multiple columns df[[' col1 ', ' col2 ']] = df[[' col1 ', ' col2 ']]. fillna (0) #replace NaN values in all columns df = df. fillna (0)
本教程解释了如何将此函数与以下 pandas DataFrame 一起使用:
import numpy as np import pandas as pd #create DataFrame with some NaN values df = pd.DataFrame({'rating': [np.nan, 85, np.nan, 88, 94, 90, 76, 75, 87, 86], 'points': [25, np.nan, 14, 16, 27, 20, 12, 15, 14, 19], 'assists': [5, 7, 7, np.nan, 5, 7, 6, 9, 9, 5], 'rebounds': [11, 8, 10, 6, 6, 9, 6, 10, 10, 7]}) #view DataFrame df rating points assists rebounds 0 NaN 25.0 5.0 11 1 85.0 NaN 7.0 8 2 NaN 14.0 7.0 10 3 88.0 16.0 NaN 6 4 94.0 27.0 5.0 6 5 90.0 20.0 7.0 9 6 76.0 12.0 6.0 6 7 75.0 15.0 9.0 10 8 87.0 14.0 9.0 10 9 86.0 19.0 5.0 7
示例1:替换列中的NaN值
下面的代码展示了如何在“note”列中用零替换 NaN 值:
#replace NaNs with zeros in 'rating' column df[' rating '] = df[' rating ']. fillna (0) #view DataFrame df rating points assists rebounds 0 0.0 25.0 5.0 11 1 85.0 NaN 7.0 8 2 0.0 14.0 7.0 10 3 88.0 16.0 NaN 6 4 94.0 27.0 5.0 6 5 90.0 20.0 7.0 9 6 76.0 12.0 6.0 6 7 75.0 15.0 9.0 10 8 87.0 14.0 9.0 10 9 86.0 19.0 5.0 7
示例2:替换多列中的NaN值
以下代码展示了如何在“grade”和“points”列中用零替换 NaN 值:
#replace NaNs with zeros in 'rating' and 'points' columns df[[' rating ', ' points ']] = df[[' rating ', ' points ']]. fillna (0) #view DataFrame df rating points assists rebounds 0 0.0 25.0 5.0 11 1 85.0 0.0 7.0 8 2 0.0 14.0 7.0 10 3 88.0 16.0 NaN 6 4 94.0 27.0 5.0 6 5 90.0 20.0 7.0 9 6 76.0 12.0 6.0 6 7 75.0 15.0 9.0 10 8 87.0 14.0 9.0 10 9 86.0 19.0 5.0 7
示例3:替换所有列中的NaN值
以下代码展示了如何将每列中的 NaN 值替换为零:
#replace NaNs with zeros in all columns df = df. fillna (0) #view DataFrame df rating points assists rebounds 0 0.0 25.0 5.0 11 1 85.0 0.0 7.0 8 2 0.0 14.0 7.0 10 3 88.0 16.0 0.0 6 4 94.0 27.0 5.0 6 5 90.0 20.0 7.0 9 6 76.0 12.0 6.0 6 7 75.0 15.0 9.0 10 8 87.0 14.0 9.0 10 9 86.0 19.0 5.0 7
您可以在此处找到fillna()函数的完整在线文档。
其他资源
以下教程解释了如何在 pandas 中执行其他常见操作: