フィルターのクリア

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

4 ビュー (過去 30 日間)
Hitesh Bugata
Hitesh Bugata 2020 年 6 月 15 日
コメント済み: Ameer Hamza 2020 年 6 月 15 日
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');
  2 件のコメント
Hitesh Bugata
Hitesh Bugata 2020 年 6 月 15 日
You're a savior, man. Thank you!
Ameer Hamza
Ameer Hamza 2020 年 6 月 15 日
I am glad to be of help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by