在矩阵变换矩阵中得到平均值

时间:2015-05-27 14:48:25

标签: python matrix pandas

我在矩阵

中得到歧义元素的意思
    import pandas as pd
    ds2 = [[ 4,  1],
           [ 5,  3],
           [ 6,  1],
           [ 7,  2],
           [ 7,  2],
           [ 8,  2],
           [12,  1],
           [ 9,  3],
           [12,  1],
           [13,  2],
           [22,  3]]
    ds2= pd.DataFrame(ds2)
    print type(ds2)
    print ds2
    ds2 = ds2.groupby(0).mean()
    print type(ds2)
    print ds2

输出:

<class 'pandas.core.frame.DataFrame'>
    0  1
0   4  1
1   5  3
2   6  1
3   7  2
4   8  2
5   9  3
6  12  1
7  13  2
8  22  3
<class 'pandas.core.frame.DataFrame'>
    1
0    
4   1
5   3
6   1
7   2
8   2
9   3
12  1
13  2
22  3

类型保持不变,但矩阵的方式看起来有变化,有没有办法在处理后保持矩阵视图?

1 个答案:

答案 0 :(得分:1)

将参数as_index=False传递给groupby方法:

In [140]:

ds2 = [[ 4,  1],
           [ 5,  3],
           [ 6,  1],
           [ 7,  2],
           [ 7,  2],
           [ 8,  2],
           [12,  1],
           [ 9,  3],
           [12,  1],
           [13,  2],
           [22,  3]]
ds2= pd.DataFrame(ds2)
ds2.groupby(0, as_index=False).mean()
Out[140]:
    0  1
0   4  1
1   5  3
2   6  1
3   7  2
4   8  2
5   9  3
6  12  1
7  13  2
8  22  3

默认情况下,任何传递的列都将用于构成索引。

来自文档:

as_index : boolean, default True
For aggregated output, return object
with group labels as the index. Only relevant for DataFrame input.
as_index=False is effectively “SQL-style” grouped output