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

在Pandas函数中调用fillna报错‘float’无fillna属性的问题排查

问题原因及解决方案

错误原因

你使用df.apply(newVars, axis=1)时,apply会逐行处理数据,把每一行作为单个Series传入newVars函数。此时函数里的df[col]取到的是该行对应列的单个float数值,而单个数值没有fillna方法,因此触发'float' has no attribute 'fillna'错误。

你的需求是处理每一列生成多列,所以应该针对列而非行来操作。

解决方案

方案1:直接循环列处理(最直观)

复制原DataFrame后,遍历每一列,对列数据生成对应的新列:

import pandas as pd

# 假设df是你的原始10列DataFrame
new_df = df.copy()

for col in df.columns:
    filled_col = df[col].fillna(0)
    # 生成填充缺失值的列
    new_df[f"{col}_filled"] = filled_col
    # 生成排名列
    new_df[f"{col}_rank"] = filled_col.rank()
    # 生成百分位排名列
    new_df[f"{col}_percentile"] = filled_col.rank(pct=True)
    # 生成减半列
    new_df[f"{col}_halved"] = df[col] / 2

每列生成4个新列,10列共生成40个新列,加上原10列,最终得到50列的DataFrame。

方案2:用自定义函数处理列(适配apply)

如果想用apply处理列,需要修改函数适配列输入(传入的是列Series),并设置axis=0(按列处理):

def newVars(col_series):
    col_name = col_series.name
    filled_col = col_series.fillna(0)
    # 返回该列对应的4个新列组成的Series
    return pd.Series(
        [filled_col, filled_col.rank(), filled_col.rank(pct=True), col_series/2],
        index=[f"{col_name}_filled", f"{col_name}_rank", f"{col_name}_percentile", f"{col_name}_halved"]
    )

# 按列应用函数,转置后拼接原DataFrame
new_cols = df.apply(newVars, axis=0).T
new_df = pd.concat([df, new_cols], axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:43:17