How can I add a column to a table based on each csv files name?

조회 수: 2 (최근 30일)
I want to write a bunch of csv files together and I am using the following code:
xx = table();
CSVfileNames = dir('*.csv');
for kk = 1:numel(CSVfileNames)
x0 = readtable(CSVfileNames(kk).name);
xx = [xx; x0];
oo=table2array(xx)
xlswrite('AllCSV',oo)
end
However, within the file I would like an additional column which has the csv file name.
So for example, the first 10 rows would be named the first csv file, the next 10 rows would be the next csv file name etc.
I tried
xx = addvars(xx,CSVfileNames,'Before','Var1');
- but this didnt work.
I am very new to Matlab so please bear with me! I found this code online and have adapted.

채택된 답변

Walter Roberson
Walter Roberson 2020년 5월 4일
filename = CSVfileNames(kk).name;
x0 = readtable(filename);
x0 = addvars(x0, repmat({filename}, height(x0), 1), 'Before', 'Var1', 'NewVariableNames', 'filename');
  댓글 수: 3
Jessica Dawson
Jessica Dawson 2020년 5월 6일
Hi Walter,
Thank you for your help with this. Initially this worked when I trialled for a small number of csv files, however, when I tried to combine over 70 files together, I now recieve an error message.
ERROR MESSAGE:
Error using tabular/addvars (line 106)
Unrecognized variable name 'Var1'.
Error in GroupCSVperCond (line 14)
x0 = addvars(x0, repmat({filename}, height (x0), 1),'Before', 'Var1', 'NewVariableNames', 'filename');
When looking at the x0 table, it seems the first row has become the variable column names (e.g NaN, which has meant there is nolonger a Var1). Is there a way to fix this? So the first row doesnt become the column names?
Thanks again for your help!
P.S I tried:
x0 =readtable(CSVfileNames(kk).name,'ReadVariableNames',false);
Walter Roberson
Walter Roberson 2020년 5월 6일
'ReadVariableNames',false should solve the problem. However, before R2020a, you might want to do a detectImportOptions on the first file and pass those options to all of the readtable().

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by