How to seperate column correctly using readtable?
7 views (last 30 days)
Show older comments
Hi,
I have been using readtable for quite some while, but for some reason I started running into problems a few days ago. Attached find an example of a .csv file. I would like to split the values from:
FLIP001,111111.1234567890,"2001-10-29 01:01:00","2001-10-29 01:01:00",7
to a table consisting of:
Var1; Var2; Var3; Var4; Var5
FLIP001; 111111.1234567890; "2001-10-29 01:01:00"; "2001-10-29 01:01:00"; 7
(Semicolons are seperating the columns here)
For some reason I do not manage to use the delimiter correctly. Can someone help me to split these variables correctly using, for instance, readtable or any other way?
Thank you!
2 Comments
Stephen23
on 10 Jun 2021
Original question by JamJam retrieved from Bing Cache (the CSV file could not be retrieved):
How to seperate column correctly using readtable?
I have been using readtable for quite some while, but for some reason I started running into problems a few days ago. Attached find an example of a .csv file. I would like to split the values from:
FLIP001,111111.1234567890,"2001-10-29 01:01:00","2001-10-29 01:01:00",7
to a table consisting of:
Var1; Var2; Var3; Var4; Var5
FLIP001; 111111.1234567890; "2001-10-29 01:01:00"; "2001-10-29 01:01:00"; 7
(Semicolons are seperating the columns here)
For some reason I do not manage to use the delimiter correctly. Can someone help me to split these variables correctly using, for instance, readtable or any other way?
Thank you!
Accepted Answer
Star Strider
on 3 Jun 2021
This appears to work —
C1 = readcell('https://www.mathworks.com/matlabcentral/answers/uploaded_files/640960/FakeCsv.csv');
CS1 = cellfun(@(x)strsplit(x,','), C1, 'Unif',0);
cellrows = cellfun(@(x)size(x,2),CS1);
CS2 = reshape([CS1{:}], cellrows(1), []).';
T1 = cell2table(CS2,'VariableNames',compose('Var%d',1:size(CS2,2)))
Completing this with the conversions:
T1.Var2 = str2double(T1.Var2);
T1.Var3 = datetime(T1.Var3, 'InputFormat','"yyyy-MM-dd HH:mm:ss"');
T1.Var4 = datetime(T1.Var4, 'InputFormat','"yyyy-MM-dd HH:mm:ss"', 'InputFormat','"yyyy-MM-dd HH:mm:ss"');
T1.Var5 = str2double(T1.Var5)
There does not appear to be a more straightforward way to parse that. The detectImportOptions options may work, however I have found those to be difficult to get right. so I went for a more direct approach.
.
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!