使用 imputer 后如何将数据放入数据框中?

Posted

技术标签:

【中文标题】使用 imputer 后如何将数据放入数据框中?【英文标题】:How can i put the data in dataframe after use imputer? 【发布时间】:2019-10-01 16:24:49 【问题描述】:

我有一些代码可以帮助我预测一些缺失值。这是代码

from datawig import SimpleImputer
from datawig.utils import random_split
from sklearn.metrics import f1_score, classification_report
df_train, df_test = random_split(df, split_ratios=[0.8, 0.2])
# Initialize a SimpleImputer model
imputer = SimpleImputer(
input_columns=['SITUACION_DNI_A'],  # columns containing information about 
 the column we want to impute
output_column='EXTRANJERO_A',  # the column we'd like to impute values for
output_path='imputer_model'  # stores model data and metrics
)

# Fit an imputer model on the train data
imputer.fit(train_df=df_train, num_epochs=10)

# Impute missing values and return original dataframe with predictions
predictions = imputer.predict(df_test)

之后我得到一个行数少于原始数据帧的新数据帧,我如何将我在预测中获得的值插入到我的原始数据帧中,或者有一种方法可以使用我的所有数据帧而不是测试

【问题讨论】:

【参考方案1】:

如果两个数据框都有一个唯一的列或可以像 ID 一样的东西,那么这个方法就可以了

df_test = df_test.set_index('unique_col')
df_test.fillna(predictions.set_index('unique_col'))

如果上述方法不起作用,则删除具有该缺失值的行并将 imputer 预测附加到数据帧。查看以下链接以获取帮助

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

Delete rows if there are null values in a specific column in Pandas dataframe

【讨论】:

以上是关于使用 imputer 后如何将数据放入数据框中?的主要内容,如果未能解决你的问题,请参考以下文章

Scikit:从 imputer 而不是 Numpy Array 返回 Dataframe 的问题

我是不是需要将文件放入熊猫数据框中以放入镶木地板格式?

如何用spass给一组数据比如说年龄分组?

将几条推文放入数据框中

如何获取每个打开窗口的名称列表并将其放入数据框中?

Pandas 如何从 JSON 索引列表并将其放入数据框中?