How can I split a .csv file after a change of value (string) in a column?
1 次查看(过去 30 天)
显示 更早的评论
Hi everybody,
Sorry for (maybe) the easy question, but I don't have any experience on splitting .csv file and the online search didn't go well. I have a .csv file that appear like this
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/170124/image.png)
I want to create different .csv file, with the same header, when there's a change in column 'ParticipantName'. How can I do this in MatLab?
Thank you for your answers!
0 个评论
回答(1 个)
Vishwanath Bailore Acharya
2018-2-13
编辑:Vishwanath Bailore Acharya
2018-2-14
Hello Riccardo,
I have reproduced the issue by creating a sample CSV file. I have split the CSV file into multiple files whenever there is a change in a column ‘Pname’.
Refer to the code below,
table = readtable('demo.csv');
names = table.Pname;
[r,c] = size(table);
k=1;
name=names{1}
start=1;
%Loop to detect a change value in the column Pname and splitting the file
%into a new CSV file.
for i=1:r
if ~strcmp(name,names{i})
t=i-1;
fileName = "party"+num2str(k)+".csv";
writetable(table(start:t,:),fileName)
start=i;
k= k+1;
name = names{i};
end
end
%Copying the rest of the values to a separate csv file
writetable(table(start:r,:),"party"+num2str(k)+".csv")
I have attached my CSV file on which I have tried this code.
Hope this solution helps with your query.
Thanks
Vishwanath Acharya
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!