How to Group data points and add serial numbers within the group ?
3 次查看(过去 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 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!