Skip to content

Commit 4c90215

Browse files
DOC: Adding examples to DataFrameGroupBy.rank #38972 (#42402)
* DOC: Adding examples to DataFrameGroupBy.rank #38972 * DOC: Adding examples to DataFrameGroupBy.rank #38972 * DOC: made the suggested changes * DOC: changed as suggested * DOC: changed as suggested * DOC: updating with black output * DOC: updating with black output * DOC: corrected docstring order
1 parent f72461f commit 4c90215

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

pandas/core/groupby/groupby.py

+36-1
Original file line numberDiff line numberDiff line change
@@ -2637,7 +2637,7 @@ def cumcount(self, ascending: bool = True):
26372637

26382638
@final
26392639
@Substitution(name="groupby")
2640-
@Appender(_common_see_also)
2640+
@Substitution(see_also=_common_see_also)
26412641
def rank(
26422642
self,
26432643
method: str = "average",
@@ -2671,6 +2671,41 @@ def rank(
26712671
Returns
26722672
-------
26732673
DataFrame with ranking of values within each group
2674+
%(see_also)s
2675+
Examples
2676+
--------
2677+
>>> df = pd.DataFrame(
2678+
... {
2679+
... "group": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
2680+
... "value": [2, 4, 2, 3, 5, 1, 2, 4, 1, 5],
2681+
... }
2682+
... )
2683+
>>> df
2684+
group value
2685+
0 a 2
2686+
1 a 4
2687+
2 a 2
2688+
3 a 3
2689+
4 a 5
2690+
5 b 1
2691+
6 b 2
2692+
7 b 4
2693+
8 b 1
2694+
9 b 5
2695+
>>> for method in ['average', 'min', 'max', 'dense', 'first']:
2696+
... df[f'{method}_rank'] = df.groupby('group')['value'].rank(method)
2697+
>>> df
2698+
group value average_rank min_rank max_rank dense_rank first_rank
2699+
0 a 2 1.5 1.0 2.0 1.0 1.0
2700+
1 a 4 4.0 4.0 4.0 3.0 4.0
2701+
2 a 2 1.5 1.0 2.0 1.0 2.0
2702+
3 a 3 3.0 3.0 3.0 2.0 3.0
2703+
4 a 5 5.0 5.0 5.0 4.0 5.0
2704+
5 b 1 1.5 1.0 2.0 1.0 1.0
2705+
6 b 2 3.0 3.0 3.0 2.0 3.0
2706+
7 b 4 4.0 4.0 4.0 3.0 4.0
2707+
8 b 1 1.5 1.0 2.0 1.0 2.0
2708+
9 b 5 5.0 5.0 5.0 4.0 5.0
26742709
"""
26752710
if na_option not in {"keep", "top", "bottom"}:
26762711
msg = "na_option must be one of 'keep', 'top', or 'bottom'"

0 commit comments

Comments
 (0)