如何使用'fillna”方法用列平均值替换 Pandas DataFrame 中的 NaN 值?
用 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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
