How to count the number of rows per group

조회 수: 8 (최근 30일)
Blue
Blue 2022년 9월 29일
답변: David Hill 2022년 9월 29일
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