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

为何使用where方法无法替换DataFrame中全部NaN值?

问题:使用where替换NaN为None后仍有残留的原因

代码示例

import pandas as pd
import numpy as np

df1 = pd.DataFrame(
    {
        'col1': [1,2,3,4,5,6,7],
        'col2': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
        'col3': [3,5,78,3,2,4,11]
    },
    columns=['col1', 'col2', 'col3']
)

df2 = pd.DataFrame(
    {
        'col1': [1,12,3,14,5,16,7],
        'col2': ['a', 'b', 'ac', 'd', 'e', 'af', 'g'],
        'col3': [3,5,78,3,21,4,1]
    },
    columns=['col1', 'col2', 'col3']
)


x = df1.compare(df2)
x = x.where(pd.notnull(x), None)

print(x)

运行输出

col1        col2        col3      
  self other  self other  self other
1  2.0  12.0  None  None   NaN   NaN
2  NaN   NaN     c    ac   NaN   NaN
3  4.0  14.0  None  None   NaN   NaN
4  NaN   NaN  None  None   2.0  21.0
5  6.0  16.0     f    af   NaN   NaN
6  NaN   NaN  None  None  11.0   1.0

提问:使用x.where(pd.notnull(x), None)后,仍有部分NaN未被替换为None,这是什么原因?


解答

核心原因是DataFrame的列数据类型限制:

  • 数值类型的列(比如col1、col3)无法存储None。在pandas中,None放入数值类型列时会被自动转换为NaN,因为数值类型(int/float)不支持非数值的None对象。
  • 字符串/object类型的列(比如col2)可以存储None,所以替换操作在这类列上生效了。

你可以通过查看结果的 dtype 验证这一点:

print(x.dtypes)

输出会显示col1、col3的子列都是float64类型,而col2的子列是object类型。

解决方法

如果需要将所有NaN替换为None,需要先把数值列转换为object类型,再执行替换:

x = df1.compare(df2).astype(object)
x = x.where(pd.notnull(x), None)
print(x)

此时所有NaN都会被替换为None,输出如下:

col1        col2        col3      
  self other  self other  self other
1    2    12  None  None  None  None
2  None  None     c    ac  None  None
3    4    14  None  None  None  None
4  None  None  None  None     2    21
5    6    16     f    af  None  None
6  None  None  None  None    11     1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:43:15