0

I have a large, two column dataframe. I use groupby to cut the dataframe up into groups of 7 entries each. However, I now wish to order each of the subgroups of 7 rows by the value in the 2nd column. How would I go about doing that?

I use

from numpy import arange
from pandas import DataFrame

df = DataFrame(etc.)

<Process the dataframe into a usable form>

groups =  df.groupby(arange(len(df.index))//7)

to split the dataframe and then I can iterate over it and print each entry with

for frame in groups:
    print(frame)

However, when it comes to manipulating the groups, sorting them and copying them into a new dataframe for final usage, I am a little stumped on how to proceed.

BaconCatBug
  • 137
  • 9
  • Does this https://stackoverflow.com/questions/27842613/pandas-groupby-sort-within-groups, this https://stackoverflow.com/questions/27018622/pandas-groupby-sort-descending-order or this https://stackoverflow.com/questions/29479357/apply-sort-to-a-pandas-groupby-operation answers your question? – Rustam A. Aug 23 '21 at 23:49
  • Thank you. The first link's lamda method, with some tweaking, worked perfectly. – BaconCatBug Aug 25 '21 at 06:51

1 Answers1

0

Solution, from: pandas groupby sort within groups

df = df.groupby(np.arange(len(df.index)) // 7, sort = False).apply(lambda x: x.sort_values(by=1, ascending=False))
BaconCatBug
  • 137
  • 9