pandas中的分层分组

时间:2016-03-01 21:43:53

标签: pandas group-by

如何使用groupby操作多个级别的数据帧?我希望能够做类似

的事情
  

data.groupby(&#39; col1&#39;)。groupby([&#39; col2&#39;,&#39; col3&#39;])。apply(foo).apply(bar)< / p>

示例数据:

    user_id year    day hour    events
0   1928375096  2015    196 0   6
1   734605009   2016    32  21  1
2   3333305045  2016    29  5   3
3   698115442   2016    30  7   11
4   685465592   2016    26  12  3
5   485945404   2016    24  10  4
6   73202588    2016    25  3   1
7   4380205067  2016    25  8   1
8   408502597   2016    32  9   1
9   584885164   2016    32  10  3

我们说col1 = user_id,col2 =&#39;年&#39;,col3 =&#39; day&#39;,因此我们每天为每个用户获取一些行(up到24)。我们想先在事件上运行foo;例如,foo(x) = (x-x.mean())/x.std(),然后我们希望将每个用户的时间序列缩减为具有bar的标量。结果数据框应包含每个用户一行。

2 个答案:

答案 0 :(得分:0)

首先,要非常认真地考虑您的问题,以确保实际上需要嵌套的groupby。这本质上是一个嵌套的for循环,因此性能可能比正常情况更快。随之而来......

In [106]: means = df.groupby('a').d.mean()

“a”列是我们最外层的分组,即评论中的“用户”。我们提前将它分组以预先计算它的意思。

In [107]: out = []

In [108]: gr = df.groupby(['a', 'b', 'c'])

In [108]: for k, v in gr:
              demeaned = v.groupby(('b', 'c')).d.transform(lambda x: x.count() * x) - means.loc[k[0]]
              out.append(demeaned)


In [109]: df['result'] = pd.concat(out)

In [110]: df
Out[110]:
     a  b  c         d    result
0    j  a  a  0.677802  1.107368
1    d  k  e -0.538711  0.032052
2    m  m  f -0.695904 -0.644055
3    m  i  i -0.433602  1.069695
4    m  e  a -2.349382 -0.560345
..  .. .. ..       ...       ...
995  e  e  m -0.626897  1.409865
996  g  m  m  0.434375 -1.402483
997  h  g  j -0.939896  1.440304
998  j  k  m -0.473171 -0.572188
999  d  c  j  0.894530  0.392441

[1000 rows x 5 columns]

然后我们处理每个小组,将结果收集在临时列表中。

public class myClass {

    public void run(String[] args) throws Exception {
        // do something with the file
    }

    public static void main(String[] args) throws Exception {
        new myClass().run(args);
    }
}

答案 1 :(得分:0)

大熊猫没有削减它,所以我交换了火焰,postgres,BigQuery(数据首先来自哪里),然后回到了大熊猫的read_gbq功能。我不情愿地编写SQL查询来通过pandas提供BiqQuery。我希望能够使用DataFrame样式的操作,但至少我正在跳过中间的CSV。