How to turn NaN values in only numerical columns into -999?
古いコメントを表示
I have some data with both numerical and string columns. See attached for an example (aa.xlsx).
It has four columns like this:
Header1 Header2 Header3 Header4
1, 4, -9, ABC123
2, NaN, 0, NaN
5, 6, NaN, ABC789
My goal is to convert any NaN values that are in only numerical columns into -999, while leaving the NaN values in string columns intact. The end results should look like something like this:
Header1 Header2 Header3 Header4
1, 4, -9, ABC123
2, -999, 0, NaN
5, 6, -999, ABC789
Here is the code I know will work, if all of my columns are numerical:
%convert any NaN into -999
T1 = readtable ('aa.xlsx', 'PreserveVariableNames',true)
Ind_table = isnan(T1{:,:});
T1{:,:}(Ind_table) = -999;
How should I modify it so that it won't do the conversion for columns that are made up of strings?
Many thanks!
採用された回答
その他の回答 (2 件)
Sebastian Bomberg
2019 年 10 月 17 日
You can have fillmissing apply only to the numeric variables directly:
fillmissing(T1,"constant",-999,"DataVariables",@isnumeric)
Walter Roberson
2019 年 10 月 17 日
fillmissing(T1,'constant',{-999,-999,-999,'NaN'})
Note that this will use the character vector 'NaN' (three characters) in place of the numeric NaN entries in column 4, as it is not possible to have numeric entries in a column devoted to character vectors.
5 件のコメント
Walter Roberson
2019 年 10 月 17 日
char_vars = varfun(@iscell, T1, 'OutputFormat', 'uniform');
constants = num2cell(-999*ones(1,width(T1)));
constants(char_vars) = {'NaN'};
new_T1 = fillmissing(T1, 'constant', constants);
Leon
2019 年 10 月 17 日
Adam Danz
2019 年 10 月 17 日
You can always unaccept / accept; I don't mind :)
Leon
2019 年 10 月 17 日
カテゴリ
ヘルプ センター および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!