pandas.api.typing.DataFrameGroupBy.nth#
- property DataFrameGroupBy.nth[source]#
Take the nth row from each group if n is an int, otherwise a subset of rows.
Deprecated since version 3.1.0: Index notation (
g.nth[n]) is deprecated in favor of callingg.nth(n)and will be removed in a future version of pandas.If dropna, will take the nth non-null row, dropna is either ‘all’ or ‘any’; this is equivalent to calling dropna(how=dropna) before the groupby.
- Returns:
- Series or DataFrame
N-th value within each group.
See also
Series.nthApply function nth to a Series.
DataFrame.nthApply function nth to each row or column of a DataFrame.
Examples
>>> df = pd.DataFrame( ... {"A": [1, 1, 2, 1, 2], "B": [np.nan, 2, 3, 4, 5]}, columns=["A", "B"] ... ) >>> g = df.groupby("A") >>> g.nth(0) A B 0 1 NaN 2 2 3.0 >>> g.nth(1) A B 1 1 2.0 4 2 5.0 >>> g.nth(-1) A B 3 1 4.0 4 2 5.0 >>> g.nth([0, 1]) A B 0 1 NaN 1 1 2.0 2 2 3.0 4 2 5.0 >>> g.nth(slice(None, -1)) A B 0 1 NaN 1 1 2.0 2 2 3.0
Specifying dropna allows ignoring
NaNvalues>>> g.nth(0, dropna="any") A B 1 1 2.0 2 2 3.0
When the specified
nis larger than any of the groups, an empty DataFrame is returned>>> g.nth(3, dropna="any") Empty DataFrame Columns: [A, B] Index: []