필터 지우기
필터 지우기

How to Group data points and add serial numbers within the group ?

조회 수: 1 (최근 30일)
Namrata Goswami
Namrata Goswami 2020년 11월 6일
댓글: Ameer Hamza 2020년 11월 6일
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!

답변 (2개)

KSSV
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

Ameer Hamza
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
Namrata Goswami
Namrata Goswami 2020년 11월 6일
The serial number should be on the occurrence of the ID. Not based on the month. I do not have a month column in the actual data.
Thanks!
Ameer Hamza
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 CenterFile Exchange에서 Preprocessing Data에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by