登录论坛

查看完整版本 : 导入具有混合数据类型的CSV文件


poster
2019-12-14, 20:13
我在MATLAB上工作了几天,而且很难将CSV文件导入矩阵。

我的问题是我的CSV文件几乎只包含字符串和一些整数值,因此csvread()不起作用。 csvread()仅与整数值csvread() 。

如何将我的字符串存储在某种二维数组中以自由访问每个元素?

这是我需要的CSV示例文件:

04;abc;def;ghj;klm;;;;; ;;;;;Test;text;0xFF;; ;;;;;asdfhsdf;dsafdsag;0x0F0F;; 最主要的是空单元格和单元格中的文本。如您所见,结构可能会有所不同。



回答:

对于这种情况,当您知道CSV文件中将有多少列数据时,像Amro建议的那样 (https://stackoverflow.com/a/4818390/52738)简单地调用textscan (https://www.mathworks.com/help/matlab/ref/textscan.html)将是您的最佳解决方案。

但是,如果您不知道先验文件中有多少列,则可以使用更通用的方法,就像我在以下函数中所做的那样。我首先使用函数fgetl (https://www.mathworks.com/help/matlab/ref/fgetl.html)将文件的每一行读入单元格数组。然后,我使用了textscan (https://www.mathworks.com/help/matlab/ref/textscan.html)函数,使用预定义的字段定界符将每一行解析为单独的字符串,并且现在将整数字段视为字符串(以后可以将其转换为数值)。这是生成的代码,放在函数read_mixed_csv :

function lineArray = read_mixed_csv(fileName, delimiter) fid = fopen(fileName, 'r'); % Open the file lineArray = cell(100, 1); % Preallocate a cell array (ideally slightly % larger than is needed) lineIndex = 1; % Index of cell to place the next line in nextLine = fgetl(fid); % Read the first line from the file while ~isequal(nextLine, -1) % Loop while not at the end of the file lineArray{lineIndex} = nextLine; % Add the line to the cell array lineIndex = lineIndex+1; % Increment the line index nextLine = fgetl(fid); % Read the next line from the file end fclose(fid); % Close the file lineArray = lineArray(1:lineIndex-1); % Remove empty cells, if needed for iLine = 1:lineIndex-1 % Loop over lines lineData = textscan(lineArray{iLine}, '%s', ... % Read strings 'Delimiter', delimiter); lineData = lineData{1}; % Remove cell encapsulation if strcmp(lineArray{iLine}(end), delimiter) % Account for when the line lineData{end+1} = ''; % ends with a delimiter end lineArray(iLine, 1:numel(lineData)) = lineData; % Overwrite line data end end 在问题的示例文件内容上运行此功能将得到以下结果:

>> data = read_mixed_csv('myfile.csv', ';') data = Columns 1 through 7 '04' 'abc' 'def' 'ghj' 'klm' '' '' '' '' '' '' '' 'Test' 'text' '' '' '' '' '' 'asdfhsdf' 'dsafdsag' Columns 8 through 10 '' '' '' '0xFF' '' '' '0x0F0F' '' '' 结果是一个3×10的单元格数组,每个单元格有一个字段,其中缺失的字段由空字符串'' 。现在,您可以访问每个单元格或单元格组合以根据需要设置其格式。例如,如果要将第一列中的字段从字符串更改为整数值,可以按以下方式使用函数str2double (https://www.mathworks.com/help/matlab/ref/str2double.html) :

>> data(:, 1) = cellfun(@(s) {str2double(s)}, data(:, 1)) data = Columns 1 through 7 [ 4] 'abc' 'def' 'ghj' 'klm' '' '' [NaN] '' '' '' '' 'Test' 'text' [NaN] '' '' '' '' 'asdfhsdf' 'dsafdsag' Columns 8 through 10 '' '' '' '0xFF' '' '' '0x0F0F' '' '' 请注意,空白字段会产生NaN (https://www.mathworks.com/help/matlab/ref/nan.html)值。



更多&回答... (https://stackoverflow.com/questions/4747834)