Clear Filters
Clear Filters

How can I split a .csv file after a change of value (string) in a column?

2 views (last 30 days)
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
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!

Answers (1)

Vishwanath Bailore Acharya
Edited: Vishwanath Bailore Acharya on 14 Feb 2018
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

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!