[英]How to do a groupby on an empty set of columns in Pandas?
I am hitting on a corner case in pandas. 我在大熊猫的一个角落里打。 I am trying to use the agg fn but without doing a groupby. 我试图使用agg fn但没有做groupby。 Say I want an aggregation on the entire dataframe
, ie 假设我想在整个dataframe
上进行聚合,即
from pandas import *
DF = DataFrame( randn(5,3), index = list( "ABCDE"), columns = list("abc") )
DF.groupby([]).agg({'a' : np.sum, 'b' : np.mean } ) # <--- does not work
And DF.agg( {'a' ... } )
does not work either. 而DF.agg( {'a' ... } )
也不起作用。
My workaround is to do DF['Total'] = 'Total'
then do a DF.groupby(['Total'])
but this seems a bit artificial. 我的解决方法是做DF['Total'] = 'Total'
然后做一个DF.groupby(['Total'])
但这看起来有点人为。
Has anyone got a cleaner solution? 有没有人有更清洁的解决方案?
It's not so great either, but for this case, if you pass a function returning True at least it wouldn't require changing df
: 它也不是那么好,但对于这种情况,如果你传递一个返回True的函数,至少它不需要改变df
:
>>> from pandas import *
>>> df = DataFrame( np.random.randn(5,3), index = list( "ABCDE"), columns = list("abc") )
>>> df.groupby(lambda x: True).agg({'a' : np.sum, 'b' : np.mean } )
a b
True 1.836649 -0.692655
>>>
>>> df['total'] = 'total'
>>> df.groupby(['total']).agg({'a' : np.sum, 'b' : np.mean } )
a b
total
total 1.836649 -0.692655
You could use various builtins instead of lambda x: True
but they're less explicit and only work accidentally. 您可以使用各种内置而不是lambda x: True
但它们不那么明确,只是偶然工作。
Having an analogous DataFrame.aggregate
method is a good idea. 使用类似的DataFrame.aggregate
方法是个好主意。 Creating an issue here: 在这里创建一个问题:
https://github.com/pydata/pandas/issues/1623 https://github.com/pydata/pandas/issues/1623
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.