adding different number of columns to specific row
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have 2 differnt csv files, i want to append the columns from book8 to book 7 based on the name column that appears in the 2 files, the name in 7 are unique but in 8 there are duplicates, so the appending columns may differ from row to another ...
is there a way to add the corresponding columns to a specific row?
i tried to append the columns in differnt ways with no success...
[M_obs,text_obs,obs]=xlsread('book7.csv');
[M_pri,text_pri,pri]=xlsread('book8.csv');
[r,c]=size(obs);
[new_matrix]=deal({});
new_matrix=obs;
for row=(2:r) %
z=find(strcmp(pri(row,1),obs(:,1)))
new_matrix(row,:)=pri(z,3:end);
end
0 commentaires
Réponses (1)
Ridwan Alam
le 30 Jan 2020
Modifié(e) : Ridwan Alam
le 30 Jan 2020
Try using the table join() method:
Example:
M_obs = readtable('book7.csv');
M_pri = readtable('book8.csv');
[~,M_pri_idx] = unique(M_pri(:,1));
M_pri_new = M_pri(M_pri_idx,:);
new_table = join(M_obs,M_pri_new,'Keys',[1,1]);
Hope this helps.
3 commentaires
Ridwan Alam
le 2 Fév 2020
Sorry, but the question is a bit confusing.
You wrote: if book8.csv has two rows of the entry "zinc543", it will append these two rows as new columns for the entry "zinc543" in book7. Can you mention which row in book 7 and book 8 has this?
Are you trying to extend the table_book_8 with columns from table_book_7 wherever available? If yes, try this code:
A=readtable('book7.csv');
B=readtable('book8.xlsx');
zSize = [size(B,1), size(B,2) + size(A,2) - 1];
zType = ["string",repmat("doublenan",[1,zSize(2)-1])];
zNew = table('Size',zSize,'VariableTypes',zType);
zVar = {B.Properties.VariableNames{:},A.Properties.VariableNames{2:end}};
zNew.Properties.VariableNames = zVar;
zNew(:,1:width(B))=B;
for i = 1:height(zNew)
zAind = find(table2array(A(:,1))==table2array(zNew(i,1)));
if ~isempty(zAind)
zNew(i,1+width(B):end) = A(zAind,2:end);
end
end
% zNew contains all of B, and adds A to wherever available
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!