필터 지우기
필터 지우기

Concatenate two columns of a csv file using horzcat with same variable name

조회 수: 4 (최근 30일)
I have few csv files, each has 3 columns with first two columns same in all. I want to merge all of them into a single csv file with first two common columns and continued with 3rd column of each individual files. Error associated is the same variable name for the 3rd column in all csv files. I'm attaching my code. Thanks in advance!
clc
clear all
close all
files = dir('*.csv');
A = readtable(files(1).name);
numfiles = length(files);
for k=2:numfiles
filename = files(k).name;
T = readtable(filename,"ReadVariableNames",true,"PreserveVariableNames",true);
A = horzcat(A, T(:,3));
end
writetable(A,'mergedCols.csv');

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 6월 15일
편집: Ameer Hamza 2020년 6월 15일
In MATLAB, two columns of a table cannot have the same variable name. Also, it might not make sense to have identical column names in a CSV file. However, you can do this using cell arrays instead of tables. Something like this
files = dir('*.csv');
A = readtable(files(1).name);
A = [A.Properties.VariableNames; table2cell(A)];
numfiles = length(files);
for k=2:numfiles
filename = files(k).name;
T = readtable(filename,"ReadVariableNames",true,"PreserveVariableNames",true);
A = horzcat(A, [T.Properties.VariableNames(3); num2cell(T{:,3})]);
end
writecell(A, 'mergedCols.csv');

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by