Convert DataFrameGroupBy object to DataFrame pandas

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

I had a dataframe and did a groupby in FIPS and summed the groups that worked fine.

kl = ks.groupby('FIPS')  kl.aggregate(np.sum) 

I just want a normal Dataframe back but I have a pandas.core.groupby.DataFrameGroupBy object.

There is a question that sounds like this one but it is not the same.

回答1:

The result of kl.aggregate(np.sum) is a normal DataFrame, you just have to assign it to a variable to further use it. With some random data:

>>> df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', >>>                         'foo', 'bar', 'foo', 'foo'], ...                  'B' : ['one', 'one', 'two', 'three', ...                         'two', 'two', 'one', 'three'], ...                  'C' : randn(8), 'D' : randn(8)}) >>> grouped = df.groupby('A') >>> grouped <pandas.core.groupby.DataFrameGroupBy object at 0x04E2F630> >>> test = grouped.aggregate(np.sum) >>> test             C         D A                       bar -1.852376  2.204224 foo -3.398196 -0.045082 


回答2:

 df_g.apply(lambda x: x)  

will return the original dataframe.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!