pandas.core.groupby.GroupBy.nth¶
- GroupBy.nth(n, dropna=None)¶
Take the nth row from each group if n is an int, or a subset of rows if n is a list of ints.
If dropna, will take the nth non-null row, dropna is either Truthy (if a Series) or ‘all’, ‘any’ (if a DataFrame); this is equivalent to calling dropna(how=dropna) before the groupby.
Parameters: n : int or list of ints
a single nth value for the row or a list of nth values
dropna : None or str, optional
apply the specified dropna operation before counting which row is the nth row. Needs to be None, ‘any’ or ‘all’
Examples
>>> df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B']) >>> g = df.groupby('A') >>> g.nth(0) A B 0 1 NaN 2 5 6 >>> g.nth(1) A B 1 1 4 >>> g.nth(-1) A B 1 1 4 2 5 6 >>> g.nth(0, dropna='any') B A 1 4 5 6 >>> g.nth(1, dropna='any') # NaNs denote group exhausted when using dropna B A 1 NaN 5 NaN