[906] Replace NaN (Not-a-Number) values with 'Null' in Pandas
In Pandas, you can replace NaN (Not-a-Number) values in a DataFrame with None
(Python's None
type) or np.nan
(NumPy's NaN) values. Here's how you can replace NaN values with None
:
import pandas as pd import numpy as np # Create a sample DataFrame with NaN values data = {'A': [1, np.nan, 3, np.nan, 5]} df = pd.DataFrame(data) # Replace NaN with None df = df.where(pd.notna(df), None) print(df)
This code replaces NaN values with None
using the where
method in Pandas.
If you want to replace NaN values with np.nan
instead, you can do it like this:
import pandas as pd import numpy as np # Create a sample DataFrame with NaN values data = {'A': [1, np.nan, 3, np.nan, 5]} df = pd.DataFrame(data) # Replace NaN with np.nan df = df.fillna(np.nan) print(df)
In this example, we're using the fillna
method to replace NaN values with np.nan
.
The choice between None
and np.nan
depends on your specific use case. If you want to work with NaN values in a more numerical context, using np.nan
is typically a better choice. If you prefer to treat NaN values as missing data in a more general sense, using None
may be more appropriate.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2022-10-17 【753】Transformer模型
2020-10-17 【492】状态转移:初识马尔科夫链
2019-10-17 【443】Tweets Analysis Q&A
2016-10-17 【229】Raster Calculator - 栅格计算器