循环遍历iterrows并用Mod中的预测值替换空值

2024-09-23 10:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个用KNN Regressor Model构建的预测值来填充一些缺少的值(NaN)。现在,我想在原始数据帧中输入预测值作为新列,保留那些不是NaN的行的原始值。这将是我的数据框架中的一个全新的列,我将用它来构建一个特性。你知道吗

我正在使用iterrows循环遍历这些值来构建一个新列,但是我得到了一个错误。我使用了两种不同的方法来分离NaN值。但是,我在每个方法中都遇到了问题

sticker_price_preds = []
features = ['region_x', 'barrons', 'type_x', 'tier_x', 'iclevel_x', 
'exp_instr_pc_2013']

for index, row in data.iterrows():
    val = row['sticker_price_2013']
    if data[data['sticker_price_2013'].isnull()]:
        f = row['region_x', 'barrons', 'type_x', 'tier_x', 'iclevel_x', 
'exp_instr_pc_2013']
        val = knn.predict(f)
    sticker_price_preds.append(val)

data['sticker_price_preds'] = sticker_price_preds

以及

sticker_price_preds = []
features = ['region_x', 'barrons', 'type_x', 'tier_x', 'iclevel_x', 
'exp_instr_pc_2013']

for index, row in data.iterrows():
    val = row['sticker_price_2013']
    if not val:
        f = row['region_x', 'barrons', 'type_x', 'tier_x', 'iclevel_x', 
'exp_instr_pc_2013']
        val = knn.predict(f)
    sticker_price_preds.append(val)

data['sticker_price_preds'] = sticker_price_preds

对于第一个方法,我将返回以下错误消息:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

对于第二种方法,NaN行保持为空


Tags: 方法datatypevalnanpriceregiontier
1条回答
网友
1楼 · 发布于 2024-09-23 10:46:20

在没有数据的情况下尝试有点困难,但是如果你想要一个向量的解决方案,这可能是可行的。创建一个具有knn.预测值,然后对数据帧进行筛选np.NaN公司你知道吗

df['predict'] = knn.predict(features)

你知道吗

data.loc[data['sticker_price_2013'].isna(),'sticker_price_2013'] = data.loc[data['sticker_price_2013'].isna(), 'predict']

相关问题 更多 >