calculating the average of a column of a csv file with specified steps and saving it in a new csv file
24 views (last 30 days)
Show older comments
Hi everyone,
I have a csv file (10081x3) which I need to take average of 2nd and 3rd column every 60 steps and save in in the new csv file in column mood not row. It means I will have new csv file of 167x3. My file contains headers and numbers start from second row. I would be happy if some one helps me. Thanks in advance.
0 Comments
Answers (3)
FannoFlow
on 22 May 2023
read table to read the CSV as a table:
use mean to calculate the mean of the 2'nd and 3'rd columns.
write the new table using writetable
2 Comments
FannoFlow
on 22 May 2023
Edited: FannoFlow
on 22 May 2023
T = readtimetable("Data_1min.csv", VariableNamingRule="preserve", TextType="string");
T.Variables = T{:,:}.erase(",");
T = convertvars(T,T.Properties.VariableNames,"double");
T = retime(T,"regular","mean",TimeStep=minutes(60));
head(T)
writetimetable(T, "Data_1min_edit.csv");
Star Strider
on 22 May 2023
This was a bit more involved than I thought it would be —
T1 = readtable('Data_1min.csv', 'VariableNamingRule','preserve')
v23 = cellfun(@str2double, strrep(T1{:,[2 3]},',','.'));
VN = T1.Properties.VariableNames;
T2 = array2table(v23);
T2 = addvars(T2, T1{:,1}, 'before',1);
T2.Properties.VariableNames = VN
M2r = reshape(T2{:,2}, 60, []);
MM2r = mean(M2r,1).';
% size(MM2r)
M3r = reshape(T2{:,3}, 60, []);
MM3r = mean(M3r,1).';
Check = [mean(T2{1:60,[2 3]}); mean(T2{61:120,[2 3]})]
D3 = T1{1:60:end,1};
T3 = table(D3,MM2r,MM3r, 'VariableNames',VN)
.
1 Comment
FannoFlow
on 22 May 2023
you're making it too hard on yourself ;)
T = readtimetable("Data_1min.csv", VariableNamingRule="preserve", TextType="string");
T.Variables = T{:,:}.erase(",");
T = convertvars(T,T.Properties.VariableNames,"double");
T = retime(T,"regular","mean",TimeStep=minutes(60));
head(T)
writetimetable(T, "Data_1min_edit.csv");
Cris LaPierre
on 22 May 2023
Here's a simple way to do this in MATLAB
opts = detectImportOptions('Data_1min.csv','VariableNamingRule','preserve');
opts = setvartype(opts,[2 3],'double');
opts = setvaropts(opts,[2 3],'ThousandsSeparator',',');
Data = readtable('Data_1min.csv',opts);
data1min = groupsummary(Data,"Var1","hour","mean",[2 3])
writetable(data1min(:,[1 3 4]),'Data_hourly.csv')
See Also
Categories
Find more on Spreadsheets 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!