2012-04-03 61 views
1

在R的doBy包中,我们对组进行汇总,并获得与原始数据相同形状和顺序的结果:什么是有效的方式在熊猫做summaryBy(...,full.dimension = T)

> require(doBy) 
> df <- data.frame(
      first = c('bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'), 
      second = c('one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'), 
      data = c(-0.424972, 0.567020, 0.276232, -1.087401, -0.673690, 0.113648, -1.478427, 0.524988)) 
> df 
    first second  data 
1 bar one -0.424972 
2 bar two 0.567020*emphasized text* 
3 baz one 0.276232 
4 baz two -1.087401 
5 foo one -0.673690 
6 foo two 0.113648 
7 qux one -1.478427 
8 qux two 0.524988 
> df['data.sum'] = summaryBy(data~first, data=df, FUN=sum, full.dimension=T)['data.sum'] 
> df 
    first second  data data.sum 
1 bar one -0.424972 0.142048 
2 bar two 0.567020 0.142048 
3 baz one 0.276232 -0.811169 
4 baz two -1.087401 -0.811169 
5 foo one -0.673690 -0.560042 
6 foo two 0.113648 -0.560042 
7 qux one -1.478427 -0.953439 
8 qux two 0.524988 -0.953439 

有没有办法做到在大熊猫一样,当DataFrame由多个指标之一进行分组?

>>> from pandas import DataFrame 
>>> df = DataFrame({ 
       'first': ['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], 
       'second': ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'], 
       'data': [-0.424972, 0.567020, 0.276232, -1.087401, -0.673690, 0.113648, -1.478427, 0.524988] }) 
>>> df = df.set_index(['first', 'second']) 
>>> s = df.groupby(level='first')['data'].sum() 
>>> df.join(s, on='first', rsuffix='.sum') 

KeyError: 'no item named first' 
+0

我发现它可以做到: 'df ['data.sum'] = s.reindex(df.index.get_level_values('first'))。values' – 2012-04-07 03:44:35

回答

2

如何:

df['data.sum'] = df.groupby('first')['data'].transform(np.sum) 

您也可以通过as_index=False到GROUPBY得到聚集,当更多的R-样的行为(或调用的结果reset_index

+0

酷!我永远不会知道这个伎俩。我需要使用'df ['data.sum'] = df.groupby(level ='first')['data']。transform(np.sum)'如果'first'已经是索引之一。谢谢。 – 2012-04-08 00:44:58

0

如何

from pandas import * 
df = DataFrame({ 
    'first': ['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], 
    'second': ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'], 
    'data': [-0.424972, 0.567020, 0.276232, -1.087401, -0.673690, 0.113648, -1.478427, 0.524988] 
}) 

df2 = df.join(df.groupby("first").sum().rename(columns={"data":"sum_data"}), 
       on="first") 
+0

谢谢,这是行不通的。但是,如果可能的话,我真的希望有索引。 – 2012-04-04 01:34:59

+0

我认为你收到了一个KeyError,因为''df''在加入之前被索引,因此'first'不再是一个加入“on”的列。为了解决这个问题,你可以在加入后设置索引吗? – Garrett 2012-04-04 16:29:39

相关问题