Matlab. 使用平均值替换缺失值

问题

如何用字符串(最常出现的类别)和数字列的平均值来替换缺失的列值?

数据示例来自于:

UCI ML Repo. Iris

例如,用‘Iris-setosa’替换NaN

enter image description here

我有的代码

它只能替换数值,但如何替换字符串呢?

function dataWithReplaced = replaceNaNWithAvg(data)dataWithReplaced = [ ];averagePerCol = table2array(varfun(@nanmean, data(: , 1:4)));for i = 1:4    dataColumn = table2array(data( : , i));    dataColumn(isnan(dataColumn)) = averagePerCol(1, i);    dataWithReplaced = [dataWithReplaced dataColumn];endend

我是MATLAB的新手,所以很多事情对我来说并不明显。


回答:

以下解决方案解决了这个问题:

由于你是MATLAB的新手,我的解决方案看起来可能会对你来说非常复杂(对我来说也看起来很复杂)。
可能有更简单的解决方案,但我找不到…

请看以下代码示例:

%创建示例数据表。%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%VarName1 = [4.9; 7.3; 6.7; 7.2; 6.5; 6.4; 6.8; 5.7; 5.8; 6.4; 6.5];VarName2 = [2.5; 2.9; 2.5; 3.6; 3.2; 2.7; 3.0; 2.5; 2.8; 3.2; 3.0];VarName3 = [4.5; 6.3; 5.8; 6.1; 5.1; 5.3; 5.5; 5.0; 5.1; 5.3; 5.5];VarName4 = [1.7; 1.8; 1.8; 2.5; 2.0; 1.9; 2.1; 2.0; 2.4; 2.3; 1.8];VarName5 = {NaN; 'aa'; 'aa'; 'bbb'; NaN; 'ccc'; 'ccc'; 'ccc'; 'ccc'; 'dddd'; 'dddd'};data = table(VarName1, VarName2, VarName3, VarName4, VarName5);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%将表格的最后一列转换为单元数组。stringColumn = table2cell(data(:, 5));%从单元数组中删除所有NaN元素%参考: https://www.mathworks.com/matlabcentral/newsreader/view_thread/314852x = stringColumn(cell2mat(cellfun(@ischar,stringColumn,'UniformOutput',0)));%在单元数组中查找最常重复的字符串:%参考: https://www.mathworks.com/matlabcentral/answers/7973-how-to-find-out-which-item-is-mode-of-cell-array%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%y = unique(x);n = zeros(length(y), 1);for iy = 1:length(y)    n(iy) = length(find(strcmp(y{iy}, x)));end[~, itemp] = max(n);commonStr = y(itemp);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%查找stringColumn中所有NaN元素的索引。nanIdx = find(cell2mat(cellfun(@ischar,stringColumn,'UniformOutput',0)) == 0);%用commonStr替换NaN值的元素。stringColumn(nanIdx) = commonStr;%替换原始表的最后一列data(:, 5) = stringColumn;

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注