Skip to content

ENH: add indexing syntax to GroupBy.nth() #44589

Closed
@johnzangwill

Description

@johnzangwill

Proposed Enhancement

#42947 added slice function arguments to groupby.nth(), but not Python slice index expressions.
I would like to be able to use Python slice notation as an alternative to the current function call.
e.g.

  • groupby.nth[b:e:s] to be the same as groupby.nth(slice(b, e, s)).
  • groupby.nth[a, b, c, ...] to be the same as groupby.nth([a, b, c, ...]).

API breaking implications

None. This is just syntactic sugar using existing functionality, and the existing API will not be changed.

Current functionality

df = df = pd.DataFrame({'A': [1, 1, 2, 1, 2],  'B': [1, 2, 3, 4, 5]}, columns=['A', 'B'])
g = df.groupby("A")
g.nth(slice(None, -1))
 	 	B
 	A 	
 	1 	1
 	1 	2
 	2 	3

Current behavior

g.nth[:-1]
 	---------------------------------------------------------------------------
 	TypeError                                 Traceback (most recent call last)
 	~\AppData\Local\Temp/ipykernel_18684/1996983145.py in <module>
 	----> 1 g.nth[0:-1]

 	TypeError: 'method' object is not subscriptable

Desired behavior

g.nth[:-1]
 	 	B
 	A 	
 	1 	1
 	1 	2
 	2 	3

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions