How to count the number of rows per group

9 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by