How to count the number of rows per group

7 次查看(过去 30 天)
Hi, I simply want to count the number of rows per group (for unique combinations of a, b and c). Groups where either a, b, or c are NaN should have a number of rows of NaN in the desired_output table.
% Original table
a = [1, 1, 1, 1, 2, 3, 3, 3]';
b = [NaN, NaN, NaN, NaN, 10, 23, 23, 23]';
c = [NaN, NaN, NaN, NaN, 5, 6, 6, 6]';
T = table(a, b, c)
T = 8×3 table
a b c _ ___ ___ 1 NaN NaN 1 NaN NaN 1 NaN NaN 1 NaN NaN 2 10 5 3 23 6 3 23 6 3 23 6
% desired_output
a = [1, 1, 1, 1, 2, 3, 3, 3]';
b = [NaN, NaN, NaN, NaN, 10, 23, 23, 23]';
c = [NaN, NaN, NaN, NaN, 5, 6, 6, 6]';
d = [NaN, NaN, NaN, NaN, 1, 3, 3, 3]';
desired_output = table(a, b, c, d)
desired_output = 8×4 table
a b c d _ ___ ___ ___ 1 NaN NaN NaN 1 NaN NaN NaN 1 NaN NaN NaN 1 NaN NaN NaN 2 10 5 1 3 23 6 3 3 23 6 3 3 23 6 3
Thank you,
  4 个评论
Image Analyst
Image Analyst 2022-9-29
I tried some ways using table2array and unique but none of them was a one-liner. If you have a few lines of code that does it, just go with that. Sometimes longer code is better because it's more readable and understandable rather than a cryptic one-liner that no one can understand.
Blue
Blue 2022-9-29
% Here is what I would attempt to go from T to desired output but Im stuck at the last row and anyhow this feels clumsy.
% Calculate number of rows per group
g = groupcounts(T, {'a', 'b', 'c'}, IncludeMissingGroups = false);
g.Percent = [];
g = renamevars(g, 'GroupCount', 'n_rows');
% Find unique combinations
[idx, idy] = ismember(T(:, {'a', 'b', 'c'}), g(:, {'a', 'b', 'c'}), 'rows');
% Assign back to T. Stuck here
% T = g(idy(idx), 4)];

请先登录,再进行评论。

采纳的回答

David Hill
David Hill 2022-9-29
A=[a,b,c];
u=unique(A,'rows');
d=zeros(size(A,1),1);
idx=any(isnan(A),2);
d(idx)=nan;
f=find(~idx);
for k=1:length(f)
d(f(k))=sum(ismember(A,A(f(k),:),'rows'));
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by