Borrar filtros
Borrar filtros

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

4 visualizaciones (últimos 30 días)
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');

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 15 de Jun. de 2020
Editada: Ameer Hamza el 15 de Jun. de 2020
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');

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by