Python - 如何在 Pandas 中用均值填充 NAN 值?
对于均值,请使用该mean()函数。用 NaN 计算列的平均值,并使用fillna()用平均值填充 NaN 值。
让我们首先导入所需的库 -
import pandas as pdimport numpy as np
创建一个包含 2 列和一些 NaN 值的 DataFrame。我们已经使用 numpy 输入了这些 NaN 值np.NaN-
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN]
}
)
使用 NaN 查找列值的平均值,即此处的 Units 列。因此,Units 列有 100、150 和 80;因此,平均值将为 110 -
meanVal = dataFrame['Units'].mean()
将 NaN 替换为其所在列的平均值。上面计算的平均值是 110,所以 NaN 值将替换为 110 -
dataFrame['Units'].fillna(value=meanVal, inplace=True)
示例
以下是代码 -
import pandas as pd输出结果import numpy as np
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, np.NaN, 80, np.NaN, np.NaN]
}
)
print"DataFrame ...\n",dataFrame
# finding mean of the column values with NaN i.e, for Units columns here
# so the Units column has 100, 150 and 80; therefore the mean would ne 110
meanVal = dataFrame['Units'].mean()
# Replace NaNs with the mean of the column where it is located
# the mean calculated above is 110, so NaN values will be replaced with 110
dataFrame['Units'].fillna(value=meanVal, inplace=True)
print"\nUpdated Dataframe after filling NaN values with mean...\n",dataFrame
这将产生以下输出 -
DataFrame ...Car Units
0 BMW 100.0
1 Lexus 150.0
2 Lexus NaN
3 Mustang 80.0
4 Bentley NaN
5 Mustang NaN
Updated Dataframe after filling NaN values with mean...
Car Units
0 BMW 100.0
1 Lexus 150.0
2 Lexus 110.0
3 Mustang 80.0
4 Bentley 110.0
5 Mustang 110.0
以上是 Python - 如何在 Pandas 中用均值填充 NAN 值? 的全部内容, 来源链接: utcz.com/z/359547.html