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

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by