Search code examples
pythonpandasgroup-bydataframealphabetical-sort

Using pandas.Dataframe.groupby without alphabetical ordering


I have a dataframe that I want to alter (according to the code right below) but it put's all the 'Experiment' name values in alphabetical order. Is there a way to leave the order as it is after calling pandas.Dataframe.groupby?

df = df.groupby(['Experiment', 'Step'], as_index=False)['value'].aggregate(np.sum)

Solution

  • groupby takes a keyword argument sort, which by default is True. You should do:

    df = df.groupby(['Experiment', 'Step'], sort=False, as_index=False)['value'].aggregate(np.sum)