Import a CSV file with no header separating numbers from symbols in a table
조회 수: 67 (최근 30일)
이전 댓글 표시
Thank you in advance for your help.
I'm trying to import a CSV file coming from an outsource company, structured this way:
A,"7,40 €"
B,"20,60 €"
C,"23,99 €"
[...]
Where the first comma is the separator for the two different columns, while the second comma is the decimal of the price.
I tried to import it using reatable('filename.csv').
what i get is similar to the following result:
ans =
1×3 table
A x7_40_
________________________________________________________________ ___________
{'B'} {'20,60 €'}
{'C'} {'23,99 €'}
What i would like to get instaed is a cell 1x3 like this
A 7.40
B 20.60
C 23.99
I can't substitute commas with dots previously otherwise it wont' recognise the two columns anymore. So i definitely need to manage the file after importing.
Is anyone so kind to please assist me in this?
Thank you.
댓글 수: 0
채택된 답변
Ive J
2020년 12월 2일
Readtable ReadVariableNames allows you this:
tab = readtable('tmp.csv', 'ReadVariableNames', false); % don't read variable names
tab.Var2 = cellfun(@(x)sscanf(x, '%f'), replace(tab.Var2, ',', '.'));
추가 답변 (1개)
dpb
2020년 12월 2일
Gotta' give it a little help...but boy! that's ugleee! :( At least they did use quoted strings.
opt=detectImportOptions('Michele.csv');
opt.VariableNamesLine=0;
opt.DataLines=[1 inf];
opt.VariableNames={'Var1','Var2'};
tMich=readtable('Michele.csv',opt);
tMich.Var1=categorical(tMich.Var1);
tMich.Var2=str2double(strrep(extractBefore(tMich.Var2,' '),',','.'));
resulted in
>> tMich
tMich =
3×2 table
Var1 Var2
____ _____
A 7.4
B 20.6
C 23.99
>>
No matter what, DetectImportOptions and readtable want to make the first row into variable names -- this is a bug or at least a quality of implementation fault in my opinion. Shouldn't have to tell it not to do that if set the VariableNamesLine to 0. That's a nit, but an annoyance if don't know about it. In your case it ate the first data line as the variable names as well by default.
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!