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

Pandas函数返回值疑问:为何有时返回值有时仅返回DataFrame名?

问题

我写了一个用Pandas计算相关向量的函数,功能是排除目标变量本身,按绝对值降序找出Top n特征。第一个函数输入参数后能正常返回计算结果:

#Correlation vector
#Excluding the target variable itself, find the top n features- ranked by absolute value desc 
def correlation_vector(d, v, n):
    corrresult = d.drop(v, axis=1).apply(lambda x: x.corr(d[v])) # <- d[v] 

    return corrresult

但在函数第4行添加dropna(inplace=True)后,函数返回的不是结果数据,反而像是变量名称?必须单独运行变量才能看到数值:

#Correlation vector
#Excluding the target variable itself, find the top n features- ranked by absolute value desc 
def correlation_vector(d, v, n):
    corrresult = d.drop(v, axis=1).apply(lambda x: x.corr(d[v])).dropna(inplace=True) 
    return corrresult

为什么会出现这种返回值差异?

原因分析

核心问题出在inplace=True这个参数的作用:

  • 当Pandas方法设置inplace=True时,它会直接在原对象上执行修改操作,不会返回任何新的对象,实际返回值是None。
  • 第二个函数里,你把dropna(inplace=True)的返回值(也就是None)赋值给了corrresult,所以函数最终返回的是None,自然看不到预期的结果。
  • 第一个函数没有用inplace=True,dropna()默认会返回一个处理后的新Series/DataFrame对象,赋值给corrresult后返回,就能得到正确的计算结果。

正确的写法有两种:

  1. 去掉inplace=True,让dropna()返回新对象:
def correlation_vector(d, v, n):
    corrresult = d.drop(v, axis=1).apply(lambda x: x.corr(d[v])).dropna()
    return corrresult
  1. 分开执行赋值和修改操作,先拿到对象再原地修改:
def correlation_vector(d, v, n):
    corrresult = d.drop(v, axis=1).apply(lambda x: x.corr(d[v]))
    corrresult.dropna(inplace=True)
    return corrresult

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:15:04