我使用MATLAB中读COVID-19数据由约翰霍普金斯大学提供的.csv的文件使用urlread
,但我不知道如何使用textscan
在下一步,以便将字符串转换成表格。.csv文件的前两列是指定区域的字符串,其后大量包含按日期记录的已感染数目的列。
目前,我只是保存urlread
本地返回的字符串,然后再打开此文件importdata
,但是肯定应该有一个更优雅的解决方案。
您混淆了两件事:您要使用“ textscan”(当然还有“ fopen”和“ fclose”)从下载的csv文件中进行读取,或者要使用“ urlread”(或者更确切地说是“ webread”)如MATLAB建议不要再使用“ urlread”。我选择后者,因为我自己从来没有做过^^
因此,首先我们读取数据并将其拆分为行
url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv";
% read raw data as single character array
web = webread(url);
% split the array into a cell array representing each row of the table
row = strsplit(web,'\n');
然后,我们分配一个表(预分配对MATLAB有利,因为它在RAM中的连续地址上存储变量,因此请事先告知MATLAB您需要多少空间):
len = length(row);
% get the CSV-header as information about the number of columns
Head = strsplit(row{1},',');
% allocate table
S = strings(len,2);
N = NaN(len,length(Head)-2);
T = [table(strings(len,1),strings(len,1),'VariableNames',Head(1:2)),...
repmat(table(NaN(len,1)),1,length(Head)-2)];
% rename columns of table
T.Properties.VariableNames = Head;
请注意,我做了一个小技巧,通过重复一个表来分配这么多“ NaN”的可修复列。但是,将这个表与字符串表合并是很困难的,因为它们都包含列名var1和var2。这就是为什么我立即重命名第一个表的列的原因。
现在我们可以实际填写表格了(由于发现将“ Korea,South”写成逗号分隔的文件很好的人,这有点讨厌)
for i = 2:len
% split this row into columns
col = strsplit(row{i},',');
% quick conversion
num = str2double(col);
% keep strings where the result is NaN
lg = isnan(num);
str = cellfun(@string,col(lg));
T{i,1} = str(1);
T{i,2} = strjoin(str(2:end));% this is a nasty workaround necessary due to "Korea, South"
T{i,3:end} = num(~lg);
end
这也将在未来的日子里发挥作用。让我知道您实际上将如何处理数据
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句