如何从表格在matlab中制作数据透视表

mje*_*sen 5 matlab pivot-table

有没有一种简单的方法可以从 matlab 中在 matlab 中制作数据透视表table?在 Excel 中还是pandas.pivot_table在 Python 中?我在文件交换中找到了pivottable.m,但它不适用于tables.

这是一个例子,如果我有一张桌子t

name     value
_____    _____

'Foo'     0   
'Bar'    -1   
'Bar'     5   
'Foo'     1   
Run Code Online (Sandbox Code Playgroud)

我想name使用该@sum函数在列上进行聚合,以获得:

name     sum_of_value
_____    ________

'Bar'    4       
'Foo'    1   
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法来做到这一点?

mje*_*sen 5

我找到了一种使用方法accumarray(可能有更好的方法):

[C,ia,ic] = unique(t.name);
pivot_table = table;
pivot_table.name = C;
pivot_table.sum_of_value = accumarray(ic, t.value, [], @sum)

pivot_table = 

name     sum_of_value
_____    ____________

'Bar'    4           
'Foo'    1  
Run Code Online (Sandbox Code Playgroud)

编辑:我将其扩展为一个函数并将其添加到 Matlab 文件交换中


Giu*_*ppe 5

您可以grpstats用于简单的汇总表。但是,用于unstack获得更复杂的枢轴。

% Example: Create columns from Var1, summing the values for each date:

T = 
    date        item      value
    ________    _______   _______
    2015.2      a         1
    2015.2      a         1
    2015.2      b         1
    2015.2      c         1
    2015.4      a         2
    2015.4      b         2
    2015.4      c         2
    2015.4      d         2
    2016.2      a         3
    2016.2      b         3
    2016.2      c         3
    2016.2      d         3


T2 = unstack(T, 'value', 'item', 'GroupingVariables', 'date', 'AggregationFunction', @sum);

T2 = 
    date        a        b        c        d   
    ________    _____    _____    _____    _____
    2015.2      2        1        1        NaN
    2015.4      2        2        2        2
    2016.2      3        3        3        3
Run Code Online (Sandbox Code Playgroud)