You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas:为布尔值设置NaN时如何规避FutureWarning?

问题描述

需要对Pandas DataFrame应用比较运算符,当源数据存在缺失值时,结果布尔表中对应位置也需保留缺失值。现有代码如下:

>>> pd.__version__
'2.1.1'
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame([[1.2, 2.2, np.nan], [1.1, np.nan, 3.3]], columns=['A', 'B', 'C'])
>>> res = df.gt(1.0)
>>> res
    A      B      C
0  True   True  False
1  True  False   True

尝试为原缺失值位置赋值pd.NA时触发FutureWarning:

>>> res[df.isna()] = pd.NA
FutureWarning: Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value 'nan' has dtype incompatible with bool, please explicitly cast to a compatible dtype first.

如何在不触发警告的前提下得到正确结果?

解决方案

方法1:转换为可空布尔类型后赋值

普通布尔类型无法存储缺失值,需先将比较结果转为Pandas的可空布尔类型(boolean),再进行缺失值赋值:

# 转换为可空布尔类型
res = df.gt(1.0).astype("boolean")
# 为原缺失值位置赋值pd.NA
res[df.isna()] = pd.NA

最终结果:

A      B      C
0   True   True  False
1   True   <NA>   True

方法2:使用where方法一步实现

通过where方法直接指定:源数据非缺失时保留比较结果,缺失位置填充pd.NA,该方法会自动适配可空布尔类型,避免类型冲突:

res = df.gt(1.0).where(df.notna(), pd.NA)

内容的提问来源于stack exchange,提问作者Karel Marik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:22:21