Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DataFrameGroupBy object to DataFrame pandas

Tags:

python

pandas

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.

like image 688
user1246428 Avatar asked Nov 27 '12 10:11

user1246428


People also ask

How do you convert a series to a DataFrame in Python?

to_frame() function is used to convert the given series object to a dataframe. Parameter : name : The passed name should substitute for the series name (if it has one).

How do I get Groupby columns in pandas?

The Hello, World! of pandas GroupBygroupby() and pass the name of the column that you want to group on, which is "state" . Then, you use ["last_name"] to specify the columns on which you want to perform the actual aggregation. You can pass a lot more than just a single column name to . groupby() as the first argument.


1 Answers

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 
like image 181
joris Avatar answered Sep 23 '22 05:09

joris