dataframe - 在 MATLAB 中按值对数据进行排序

标签 dataframe matlab

我有一个包含各种值的数据表。它包括以下列:

| 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

最佳答案

这听起来像是 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);

关于dataframe - 在 MATLAB 中按值对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74363931/

相关文章:

python - 如何使用pyspark创建包含大量列和日期数据的数据框?

python - 在 python 中创建一个带有列表的数据框

r - 将 R 中的数据帧连接/合并到向量类型单元中

algorithm - 如何在 scilab 中查看有向无环图作为输出?

R 重复数据框元素

python - pandas GroupBy 中按列表列分组

matlab - 使用 matlabdomain 时导入模块失败

matlab - 测试点是否在矩形内

matlab - 使用 Matlab 绘制 3-D RGB 立方体模型

matlab - 我如何从 MATLAB 中的 N 个点中随机选择一个点?