slaw
slaw

Reputation: 6869

Column Order in Pandas Groupby Agg Function

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)

Upvotes: 15

Views: 6878

Answers (2)

Justislav Bogevolnov
Justislav Bogevolnov

Reputation: 171

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),
                ]) )

Upvotes: 17

Paul H
Paul H

Reputation: 68146

You can use some indexing tricks to get the columns in the order you want:

g = df.groupby(['people'])
col_order = ['C', 'B', 'A']
agg_fnxs = [len, len, len]
agg_dict = dict(zip(col_rder, agg_fnxs))
g['people'].agg(agg_dict)[col_corder]

Upvotes: 4

Related Questions