我正在进行泰坦尼克号卡格尔号竞赛,目前我正在尝试估算缺失的Age
值
其思想是计算训练集上每个[Pclass, Sex]
组的平均Age
,然后使用此信息替换训练集和测试集上的NaN
这就是我到目前为止所做的:
meanAgeTrain = train.groupby(['Pclass', 'Sex'])['Age'].transform('mean')
for df in [train, test]:
df['Age'] = df['Age'].fillna(meanAgeTrain)
问题是,这仍然会在测试集中留下一些NaN值,同时在训练集中消除所有NaN。我想这与指数有关
我需要的是:
如何使用熊猫正确地做到这一点
编辑:
谢谢你的建议。@Reza的那个很有效,但我不是100%理解。所以我正试图想出我自己的解决办法
这是可行的,但我对熊猫还不熟悉,我想知道是否有更简单的方法来实现它
trainMeans = self.train.groupby(['Pclass', 'Sex'])['Age'].mean().reset_index()
def f(x):
if x["Age"] == x["Age"]: # not NaN
return x["Age"]
return trainMeans.loc[(trainMeans["Pclass"] == x["Pclass"]) & (trainMeans["Sex"] == x["Sex"])]["Age"].values[0]
self.train['Age'] = self.train.apply(f, axis=1)
self.test['Age'] = self.test.apply(f, axis=1)
尤其是函数中的if在我看来不是一个最佳实践。我需要一种方法将函数仅应用于NaN ages
编辑2:
事实证明,重置索引会使事情变得更加复杂和缓慢,因为在分组后,索引已经是我想要用作映射键的东西了。这会更快更容易:
trainMeans = self.train.groupby(['Pclass', 'Sex'])['Age'].mean()
def f(x):
if not np.isnan(x["Age"]): # not NaN
return x["Age"]
return trainMeans[x["Pclass"], x["Sex"]]
self.train['Age'] = self.train.apply(f, axis=1)
self.test['Age'] = self.test.apply(f, axis=1)
这可以进一步简化吗
用平均值填充nan值
nans
李>从RandomForestRegressionor中填充nan值
groupby与rfr的比较
计算随机训练集上的平均值
nan
值pclass
和sex
被设置为索引,这就是.fillna
的工作方式李>train
是数据的67%,而test
是数据的33%。test_size
和train_size
可以根据需要设置,如^{您可以首先为
Age
创建映射:然后将其与测试和训练单独合并,以便解决索引问题
相关问题 更多 >
编程相关推荐