如何在Pandas中的一组空列上做groupby? [英] How to do a groupby on an empty set of columns in Pandas?
问题描述
我正在打熊猫的角落案件。我正在尝试使用agg fn,但没有进行groupby。假设我想要在整个 dataframe
上进行汇总,即来自熊猫的
I am hitting on a corner case in pandas. I am trying to use the agg fn but without doing a groupby. Say I want an aggregation on the entire dataframe
, i.e.
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
并且 DF.agg({'a'...})
也不起作用。
我的解决方法是做 DF ['Total'] ='Total'
然后做一个 DF.groupby(['Total'])
但这似乎有点虚假。
My workaround is to do DF['Total'] = 'Total'
then do a DF.groupby(['Total'])
but this seems a bit artificial.
有没有人有更清晰的解决方案?
Has anyone got a cleaner solution?
推荐答案
它也不是很好,但是对于这种情况,如果传递一个返回True的函数,至少不需要更改 df
:
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
:
>>> 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
您可以使用各种内置函数而不是 lambda x:True
但他们不那么明确,只是偶然地工作。
You could use various builtins instead of lambda x: True
but they're less explicit and only work accidentally.
这篇关于如何在Pandas中的一组空列上做groupby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!