October 22, 2024
Chicago 12, Melborne City, USA
python

In pandas, how can I get a version of nth() to act as an aggregator?


In Pandas v1.x.x,

df.groupby("col").nth(0)

returned a dataframe that had "col" as the index col.

Now in pandas v2.x.x it doesn’t, and my understanding of why is that nth is now seen as a "filter" and not an "aggregator".

I saw some threads that suggested I instead do

 df.groupby("col").nth(0).reset_index().set_index("col")

If I wanted a result with "col" as the index. This strikes me as crazy wordy, and duplicates code since I have to say "col" twice.

Is there a better, cleaner way to do this? Bonus points if it is backwards compatible.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video