calculating the average of a column of a csv file with specified steps and saving it in a new csv file
22 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
FannoFlow
2023-5-22
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 个评论
FannoFlow
2023-5-22
编辑:FannoFlow
2023-5-22
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
2023-5-22
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 个评论
FannoFlow
2023-5-22
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
2023-5-22
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')
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!