用 Pandas DataFrame 中的列平均值替换 NaN 值
处理主要由实数填充的 DataFrame 中的缺失数据时,替换 NaN具有适当替代方案的价值观至关重要。在这种情况下,我们寻求用 NaN 值所在列的平均值来替换它们。
为了满足这一需求,pandas 提供了一种方便的方法:DataFrame.fillna。通过利用此函数,我们可以直接用列平均值填充 NaN 值:
<code class="python">df = ... # Your DataFrame with NaN values # Calculate the mean of each column column_means = df.mean() # Replace NaN values with the column averages filled_df = df.fillna(column_means)</code>
DataFrame.fillna 方法接受各种输入作为填充值,包括标量、字典或系列。在本例中,我们传递column_means,这是一个包含每列平均值的系列。
这里有一个示例来说明该过程:
<code class="python">import pandas as pd df = pd.DataFrame({ 'A': [-0.166919, -0.297953, -0.120211, NaN, NaN, -0.788073, -0.916080, -0.887858, 1.948430, 0.019698], 'B': [0.979728, -0.912674, -0.540679, -2.027325, NaN, NaN, -0.612343, 1.033826, 1.025011, -0.795876], 'C': [-0.632955, -1.365463, -0.680481, 1.533582, 0.461821, NaN, NaN, NaN, -2.982224, -0.046431] }) print(df) # Calculate the mean of each column column_means = df.mean() # Replace NaN values with the column averages filled_df = df.fillna(column_means) print(filled_df)</code>
输出:
A B C 0 -0.166919 0.979728 -0.632955 1 -0.297953 -0.912674 -1.365463 2 -0.120211 -0.540679 -0.680481 3 NaN -2.027325 1.533582 4 NaN NaN 0.461821 5 -0.788073 NaN NaN 6 -0.916080 -0.612343 NaN 7 -0.887858 1.033826 NaN 8 1.948430 1.025011 -2.982224 9 0.019698 -0.795876 -0.046431 A B C 0 -0.166919 0.979728 -0.632955 1 -0.297953 -0.912674 -1.365463 2 -0.120211 -0.540679 -0.680481 3 -0.151121 -2.027325 1.533582 4 -0.151121 -0.231291 0.461821 5 -0.788073 -0.231291 -0.530307 6 -0.916080 -0.612343 -0.530307 7 -0.887858 1.033826 -0.530307 8 1.948430 1.025011 -2.982224 9 0.019698 -0.795876 -0.046431
如图所示,NaN 值已替换为适当的列平均值,提供完整且一致的 DataFrame。
以上是如何使用'fillna”方法用列平均值替换 Pandas DataFrame 中的 NaN 值?的详细内容。更多信息请关注PHP中文网其他相关文章!