我有一個包含各種值的資料表。它包括以下列:
| Value 1 | Value 2 |
|---------|---------|
|0 |235 |
|1 |123 |
|1 |309 |
|1 |540 |
|2 |34 |
|3 |123 |
|3 |959 |
|3 |3939 |
我想有一個Value 2取決于每個值的表Value 1。它看起來像這樣:
| Value 1 | Value 2 |
| --------|----------------|
| 0 |[235] |
|1 |[123, 309, 540] |
|2 |[34] |
|3 |[123, 959, 3939]|
或類似的東西。
我嘗試了幾種解決方案,例如:
t = table;
for i=1:length(existing_table)
t(existing_table, end 1) = existing_table.value2(i) % append to case i
end;
--> returns Error using ()
Right hand side of an assignment into a table must be another table or a cell array.
--------------
t = table;
for i=1:length(existing_table)
switch existing_table.value2(i)
case 0
t(0, end 1) = existing_table.value2(i) % append to case
0
% etc...
end;
end;
--> returns Error using ()
Right hand side of an assignment into a table must be another table or a cell array.
--------------
t = table;
t.v1 = value1;
t.v2 = unique(value2) % Does not return the kind of table that I would like
uj5u.com熱心網友回復:
這聽起來像是一份作業accumarray:
% Create sample data
value1 = [0 1 1 1 2 3 3 3].';
value2 = [235 123 309 540 34 123 959 3939].';
T = table(value1,value2);
% Accumarray handles only positive indexes. Get these in idx using unique
[uni,~,idx] = unique(T.value1(:));
% First colum is just the unique value in the first column of T
value1_out = uni;
% accumarray groups the values corresponding to each index. Then @(x) {x}
% gathers it into a cell array
value2_out = accumarray(idx,T.value2,[],@(x) {x});
Tout = table(value1_out,value2_out);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/531270.html
標籤:数据框matlab
