How to count the number of rows per group

8 Ansichten (letzte 30 Tage)
Blue
Blue am 29 Sep. 2022
Beantwortet: David Hill am 29 Sep. 2022
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 Kommentare
Image Analyst
Image Analyst am 29 Sep. 2022
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 am 29 Sep. 2022
% 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)];

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

David Hill
David Hill am 29 Sep. 2022
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

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by