Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column Order in Pandas Groupby Agg Function

Tags:

python

pandas

Is there an automated way to maintain the order of the columns ('C', 'B', 'A') for the dataframe that is returned?

g = df.groupby(['people'])
g['people'].agg({'C' : len,
                 'B' : len,
                 'A' : len,
                })

This will return a the columns as A, B, C rather than C, B, A.

I can only find examples but not the documentation for the agg function itself.

This seems to be a workaround:

g = df.groupby(['people'])
g['people'].agg({'C' : len,
                 'B' : len,
                 'A' : len,
                }).reindex_axis(['C','B','A'], axis=1)
like image 788
slaw Avatar asked Nov 14 '14 21:11

slaw


People also ask

How do I sort a Groupby column in pandas?

Sort within Groups of groupby() Result in DataFrameBy using DataFrame. sort_values() , you can sort DataFrame in ascending or descending order, before you use this first group the DataFrame rows by using DataFrame. groupby() method. Note that groupby preserves the order of rows within each group.

Does pandas Groupby maintain order?

Groupby preserves the order of rows within each group.

How do I rearrange the order of columns in pandas?

Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.

How do you sort values after Groupby pandas?

To group Pandas dataframe, we use groupby(). To sort grouped dataframe in ascending or descending order, use sort_values(). The size() method is used to get the dataframe size.


1 Answers

OrderedDict worked surprisingly with pandas-0.18.0-py2.7:

from collections import OrderedDict
g = df.groupby(['people'])
g['people'].agg( OrderedDict([
                 ('C' , len),
                 ('B' , len),
                 ('A' , len),
                ]) )
like image 65
Justislav Bogevolnov Avatar answered Sep 28 '22 07:09

Justislav Bogevolnov