给定一个包含许多NaN
的Matlab表,如何将此表写为excel或csv文件,其中NaN被空格替换?
我使用以下功能:
T = table(NaN(5,2),'VariableNames',{'A','C'})
writetable(T, filename)
我不想用零替换它。我想要输出文件:
答案 0 :(得分:5)
你需要xlswrite
。它用空白替换NaN
s。使用table2cell
或table2array
和num2cell
的组合将表格转换为单元格数组。使用表的VariableNames
属性检索变量名称并使用单元格数组填充它们。
data= [T.Properties.VariableNames; table2cell(T)];
%or data= [T.Properties.VariableNames; num2cell(table2array(T))];
xlswrite('output',data);
示例运行:
T = table([1;2;3],[NaN; 410; 6],[31; NaN; 27],'VariableNames',{'One' 'Two' 'Three'})
T =
3×3 table
One Two Three
___ ___ _____
1 NaN 31
2 410 NaN
3 6 27
的产率:
虽然上面的解决方案在我看来比较简单但是如果你真的想使用writetable
那么:
tmp = table2cell(T); %Converting the table to a cell array
tmp(isnan(T.Variables)) = {[]}; %Replacing the NaN entries with []
T = array2table(tmp,'VariableNames',T.Properties.VariableNames); %Converting back to table
writetable(T,'output.csv'); %Writing to a csv file
答案 1 :(得分:2)
老实说,我认为以您描述的格式输出数据的最直接方式是使用xlswrite
作为Sardar did in his answer。但是,如果确实想要使用writetable
,我能想到的唯一选择是将表中的每个值封装在cell array中并替换nan
带有空单元格的条目。从此示例表T
开始,包含随机数据和nan
值:
T = table(rand(5,1), [nan; rand(3,1); nan], 'VariableNames', {'A', 'C'});
T =
A C
_________________ _________________
0.337719409821377 NaN
0.900053846417662 0.389738836961253
0.369246781120215 0.241691285913833
0.111202755293787 0.403912145588115
0.780252068321138 NaN
以下是进行转换的一般方法:
for name = T.Properties.VariableNames % Loop over variable names
temp = num2cell(T.(name{1})); % Convert numeric array to cell array
temp(cellfun(@isnan, temp)) = {[]}; % Set cells with NaN to empty
T.(name{1}) = temp; % Place back into table
end
这就是表T
最终看起来像:
T =
A C
___________________ ___________________
[0.337719409821377] []
[0.900053846417662] [0.389738836961253]
[0.369246781120215] [0.241691285913833]
[0.111202755293787] [0.403912145588115]
[0.780252068321138] []
现在您可以将其输出到writetable
的文件:
writetable(T, 'sample.csv');