Groupby 3 columns and just keep the smallest 5 for each group

Viewed 81

First of all, sorry I'm not an english native, but I hope you'll understand my question anyway ;-)

I've got a list with data from the cablenetwork provider I'm working with.

I've groupped these information by

traffic.groupby(["HUB","FIBER_NODES","WEEK"])

This worked fine, I'm getting all the information for each HUB-NODES-WEEK group. But now I want to check the traffic development. For this I want to get the difference between the average of the first and the last 5 weeks in this dataframe.

For this, I don't want to keep als the calendar weeks between 1 and 38. I just want to keep 1 to 5 or 34 to 38.

I tried:

traffic.groupby(["HUB","FIBER_NODES","WEEK"]).nlargest(5)

error: AttributeError: Cannot access callable attribute 'nlargest' of 'DataFrameGroupBy' objects, try using the 'apply' method

Next try:

traffic.groupby(["HUB","FIBER_NODES","WEEK"]).apply(lambda grp: grp.nlargest(5,"WEEK"))

This didn't worked, I still got all weeks from 1 to 38.

Does somebody have an idea what I could try next? ;-)

Thank you very much

Marco

1 Answers

I think @jon-clements in the comments has the right idea. The problem is that you included "WEEK" in the groupby. Removing it works for me (on different data):

traffic.groupby(["HUB","FIBER_NODES"]).apply(lambda grp: grp.nlargest(5,"WEEK"))

(I would also have expected nlargest to work, but apparently it hasn't been implemented for DataFrame groupbys. :-/)

Related