Import .csv with missing delimiters and values

조회 수: 15 (최근 30일)
Henrik Haussmann
Henrik Haussmann 2021년 6월 2일
편집: Cris LaPierre 2022년 4월 4일
I am trying to import some (generated) .csv files into MATLAB. Unfortunately, some of the files have rows with blank entries AND missing delimiters (in my case a semi-colon is the delimiter). This means when I am trying to import the .csv file using readtable, the dimensions of the table are wrong, i.e. MATLAB is confused and packs the data in cells. I need the table to be the right size so that I can use it later on.
An example .csv file would look like this:
date;time;var1;var2;var3
02.06.21;15:00:00;1;2;3
02.06.21;16:00:00;4
02.06.21;17:00:00;5;6;7
As you can see, there are missing values in the second row AND the delimiters are also missing. Is there any way I can import the .csv file so that the table has the width of the widest row, and that the needed delimiters would be added automatically (I don't really care about the value that would be put in these spaces but I need the format).
Thanks for any help in advance!

채택된 답변

Cris LaPierre
Cris LaPierre 2021년 6월 2일
편집: Cris LaPierre 2022년 4월 4일
I am able to use readtable to load the data you have shared without any trouble. It does not put the data into a cell, and it fills the missing columns with NaN.
% No options set. Year is wrong, but table width is correct.
attempt1 = readtable("HH_file.csv")
attempt1 = 3×5 table
date time var1 var2 var3 __________ ________ ____ ____ ____ 02.06.0021 15:00:00 1 2 3 02.06.0021 16:00:00 4 NaN NaN 02.06.0021 17:00:00 5 6 7
% Now add some formatting to date and time
opts = detectImportOptions("HH_file.csv");
opts = setvartype(opts,"date",'datetime');
opts = setvaropts(opts,"date",'InputFormat','dd.MM.yy');
opts = setvartype(opts,"time",'duration');
opts = setvaropts(opts,"time",'InputFormat','hh:mm:ss');
attempt2 = readtable("HH_file.csv",opts)
attempt2 = 3×5 table
date time var1 var2 var3 ________ ________ ____ ____ ____ 02.06.21 15:00:00 1 2 3 02.06.21 16:00:00 4 NaN NaN 02.06.21 17:00:00 5 6 7
I didn't have R2020a installed, but I did test this code in R2019b. It worked there.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by