【问题标题】:Average values in one column when another column repeats当另一列重复时,一列中的平均值
【发布时间】:2015-01-17 19:33:52
【问题描述】:

我在 MATLAB 中有一个看起来像这样的表(仅用于说明目的。数字不一定正确):

Monitor ID              POC Latitude    Longitude   Date Local  Mean  Date Num
'01-003-0010-88101'     1   30.498001   -87.881412  1/1/2012    6.7   734869
'01-003-0010-88101'     3   30.498001   -87.881412  1/4/2012    9     734872
'01-003-0010-88101'     1   30.498001   -87.881412  1/7/2012    6.5   734875

'01-073-0023-88101'     1   33.447867   -117.088649 1/22/2012   8     734890
'01-073-0023-88101'     3   33.447867   -117.088649 1/22/2012   6     734890
'01-073-0023-88101'     9   33.447867   -117.088649 1/22/2012   9.6   734890

可以在此处找到包含更多列的完整表: https://www.dropbox.com/s/q6psz0eqhf1c7gl/data_PM25_table.mat.mat?dl=0

我想要做的是,如果数据在同一天来自同一个地方,那么平均最后一列(算术平均值)。

因此,如果在 Date Num 相同时 Monitor ID 重复(即,一个监视器在特定日期有多个值,则平均算术平均值。

我上面给出的表格有两个例子来说明我的意思。

  • 前三行是我不理会的行 - 日期不同,因此这是来自三个不同日期的数据。我会在这些日子的每一天添加一个带有数字“1”POC 的新列。

  • 但是,之后的三行具有相同的日期和不同的 POC 值。在这种情况下,我会将三个平均值取平均值,因为测量值来自同一天的同一地点。

我只想保留同一天同一地点的数据之一。

所以经过处理后,我希望表(可以是新表)看起来像这样:

Monitor ID              POC Latitude    Longitude   Date Local  Mean  Date Num   Counter
'01-003-0010-88101'     1   30.498001   -87.881412  1/1/2012    6.7   734869     1
'01-003-0010-88101'     3   30.498001   -87.881412  1/4/2012    9     734872     1
'01-003-0010-88101'     1   30.498001   -87.881412  1/7/2012    6.5   734875     1

'01-073-0023-88101'     1   33.447867   -117.088649 1/22/2012   7.9   734890     3

我该怎么做?

【问题讨论】:

  • 您有用于构建此表的代码或数据集吗?如果我们必须用您自己提供的内容手动构建一个表格,则很难为您提供解决方案。
  • @rayryeng 我已经添加了实际表的 .mat 文件,并处理了更多数据。希望问题更清楚。

标签: matlab find average


【解决方案1】:

不要尝试对整个表格执行此操作,而是单独拉出每个站点。然后,对日期进行排序,找出这些日期重复的位置和次数。这样,可以很容易地找到平均值。

for m = 1:length(u_id) % Run through one site at a time
    k = u_id(m); % Site under consideration

    ind1 = find(strcmp(data_PM25.MonitorID, k) == 1); % Find where a site has data
    d1 = data_PM25(ind1,:); % Data set with only one site
    [dates_sort ind_sort] = sort(cell2mat(d1.DateNum)); % Sort the dates
    d1 = d1(ind_sort,:); % Make sure the entire table is sorted in the same way

    [aa, ii, jj] = unique(dates_sort,'legacy'); % Unique dates
    n = diff([0; ii]); % Find how many times each monitor repeats on one day
    result = accumarray(jj,vertcat(d1.ArithmeticMean(ind_sort)))./n; % Data in repeated rows are summed and divided by the number of repetitions to obtain the averages

    d2 = d1(ii,:); % Create dataset with only the average of the arithmetic means
    d2.ArithmeticMean = result; % Set the Arithmetic Mean to the new averaged mean over all POCs at a site on a particular day
    d2.NumberOfPOCs = n; % Number of POCs being averaged together
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多