【发布时间】:2021-08-10 21:12:03
【问题描述】:
我是学习 pandas 的新手,刚刚学习了 python,所以我的问题可能看起来很傻。我创建了一个函数来更改数据集中的空值。我试图在我的数据框的几列上调用该函数。
def impute_age(cols):
age = cols[0]
pclass = cols[1]
if pd.isnull(Age):
if pclass == 1:
return 37
elif pclass ==2:
return 29
else:
return 23
else:
return Age
然后我这样称呼它:
train['Age'] = impute_age(train[['Age','Pclass']])
给出的关键错误:0
我在某处检查过,他使用了这样的方式:
train['Age'] = train[['Age','Pclass']].apply(impute_age,axis=1)
但在python 中,我们调用了上述函数。谁能告诉我我在这里做错了什么。
【问题讨论】:
-
您的函数的设计方式不是让您可以将 DateFrame 作为输入。对于这种情况,我建议使用
numpy.select。 -
如果你想使用布尔索引,你应该使用
df.iloc[: , colIndex]。当您只使用0时,pandas 认为它是列标签而不是索引。所以这就是你错误的原因。但是有更好的方法来实现您在替换 NaN 值时尝试做的事情。numpy.where()、numpy.select()和df.where()就是这样的方式。
标签: python pandas dataframe numpy data-science