Skip to content

Commit 2c55f28

Browse files
sinhrksjreback
authored andcommitted
DOC: Fix groupby nth (#13810)
1 parent aa88215 commit 2c55f28

File tree

1 file changed

+39
-16
lines changed

1 file changed

+39
-16
lines changed

pandas/core/groupby.py

+39-16
Original file line numberDiff line numberDiff line change
@@ -1205,32 +1205,55 @@ def nth(self, n, dropna=None):
12051205
12061206
Examples
12071207
--------
1208-
>>> df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
1208+
1209+
>>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
1210+
... 'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B'])
12091211
>>> g = df.groupby('A')
12101212
>>> g.nth(0)
1211-
A B
1212-
0 1 NaN
1213-
2 5 6
1213+
B
1214+
A
1215+
1 NaN
1216+
2 3.0
12141217
>>> g.nth(1)
1215-
A B
1216-
1 1 4
1218+
B
1219+
A
1220+
1 2.0
1221+
2 5.0
12171222
>>> g.nth(-1)
1218-
A B
1219-
1 1 4
1220-
2 5 6
1223+
B
1224+
A
1225+
1 4.0
1226+
2 5.0
1227+
>>> g.nth([0, 1])
1228+
B
1229+
A
1230+
1 NaN
1231+
1 2.0
1232+
2 3.0
1233+
2 5.0
1234+
1235+
Specifying ``dropna`` allows count ignoring NaN
1236+
12211237
>>> g.nth(0, dropna='any')
1222-
B
1223-
A
1224-
1 4
1225-
5 6
1238+
B
1239+
A
1240+
1 2.0
1241+
2 3.0
12261242
12271243
NaNs denote group exhausted when using dropna
12281244
1229-
>>> g.nth(1, dropna='any')
1245+
>>> g.nth(3, dropna='any')
12301246
B
1231-
A
1247+
A
12321248
1 NaN
1233-
5 NaN
1249+
2 NaN
1250+
1251+
Specifying ``as_index=False`` in ``groupby`` keeps the original index.
1252+
1253+
>>> df.groupby('A', as_index=False).nth(1)
1254+
A B
1255+
1 1 2.0
1256+
4 2 5.0
12341257
"""
12351258

12361259
if isinstance(n, int):

0 commit comments

Comments
 (0)