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)
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.
Groupby preserves the order of rows within each group.
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.
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.
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),
]) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With