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

Pandas DataFrame中fillna()方法失效问题求助(泰坦尼克数据集)

泰坦尼克数据集缺失值填充无效的解决办法

你遇到的问题核心是pandas的fillna方法默认不会修改原DataFrame,而是返回一个填充后的新对象,你只调用了方法但没保存结果,所以原数据里的NaN还在。另外fillna()不带参数会报错,因为必须指定填充值(比如你之前用的'')。

有两种正确的处理方式:

方法1:将填充结果赋值给原变量

把fillna返回的新DataFrame重新赋值给titanic_excel,这样原变量就会被替换成填充好的数据:

import pandas as pd
# 路径加r前缀避免转义字符问题
titanic_excel = pd.read_excel(r"C:\Users\mithi\OneDrive\Desktop\pyps\Domain-wise Task 2\titanic_excel.xlsx")

# 保存填充后的结果
titanic_excel = titanic_excel.fillna('')
print(titanic_excel.head())

方法2:使用inplace=True参数直接修改原数据

在fillna里加上inplace=True,会直接在原DataFrame上修改,不需要重新赋值:

import pandas as pd
titanic_excel = pd.read_excel(r"C:\Users\mithi\OneDrive\Desktop\pyps\Domain-wise Task 2\titanic_excel.xlsx")

# 直接修改原数据集
titanic_excel.fillna('', inplace=True)
print(titanic_excel.head())

两种方法都能让你看到填充后的结果,不会再保留原来的NaN值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:57:09