How to Group data points and add serial numbers within the group ?
조회 수: 1 (최근 30일)
이전 댓글 표시
I have a table with ID and Date columns. I want to group the data by ID and add serial numbers in a new column call Serial No. as seen in the example below. How to do this in Matlab ?
Original table:
ID Date
12 jan
12 feb
12 mar
14 jan
14 feb
14 mar
14 apr
11 jan
11 feb
Expected Output:
ID Date Serial No.
12 jan 1
12 feb 2
12 mar 3
14 jan 1
14 feb 2
14 mar 3
14 apr 4
11 jan 1
11 feb 2
Thanks!
댓글 수: 0
답변 (2개)
KSSV
2020년 11월 6일
A = [12 1
12 2
12 3
14 1
14 2
14 3
14 4
11 1
11 2] ;
[c,ia,ib] = unique(A(:,1)) ;
n = length(c) ;
iwant = zeros(n,2) ;
for i = 1:n
iwant(i,1) = c(i) ;
iwant(i,2) = sum(A(ib==i,2)) ;
end
iwant
댓글 수: 0
Ameer Hamza
2020년 11월 6일
See this example
ID = [1;1;2;2;2];
Date = {'jan', 'feb', 'jan', 'feb', 'mar'}.';
T = table(ID, Date);
T.Serial_no = month(datetime(T.Date, 'InputFormat', 'MMM'));
Result
>> T
T =
5×3 table
ID Date Serial_no
__ _______ _________
1 {'jan'} 1
1 {'feb'} 2
2 {'jan'} 1
2 {'feb'} 2
2 {'mar'} 3
댓글 수: 2
Ameer Hamza
2020년 11월 6일
In that case, try this
ID = [1;1;2;2;2];
Date = {'jan', 'feb', 'jan', 'feb', 'mar'}.';
T = table(ID, Date);
T.Serial_no = cell2mat(splitapply(@(x) {(1:numel(x)).'}, T.ID, T.ID));
참고 항목
카테고리
Help Center 및 File Exchange에서 Preprocessing Data에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!