Skip to content

Commit a8d9b00

Browse files
committed
Initial working rank with no tiebreaker
1 parent f391cbf commit a8d9b00

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

pandas/_libs/groupby_helper.pxi.in

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,39 @@ def group_nth_{{name}}(ndarray[{{dest_type2}}, ndim=2] out,
444444
else:
445445
out[i, j] = resx[i, j]
446446

447+
448+
@cython.boundscheck(False)
449+
@cython.wraparound(False)
450+
def group_rank_{{name}}(ndarray[{{dest_type2}}, ndim=2] out,
451+
ndarray[{{c_type}}, ndim=2] values,
452+
ndarray[int64_t] labels,
453+
bint is_datetimelike):
454+
"""
455+
Only transforms on axis=0
456+
"""
457+
cdef:
458+
Py_ssize_t i, j, N, K
459+
int64_t lab, idx, counter=1
460+
ndarray[int64_t] _as
461+
462+
N, K = (<object> values).shape
463+
464+
_as = np.lexsort((values[:, 0], labels))
465+
466+
with nogil:
467+
for i in range(N):
468+
idx = _as[i]
469+
lab = labels[idx]
470+
if i > 0 and lab == labels[_as[i-1]]:
471+
counter += 1
472+
else:
473+
counter = 1
474+
if lab < 0:
475+
continue
476+
477+
for j in range(K):
478+
out[idx, j] = counter
479+
447480
{{endfor}}
448481

449482
#----------------------------------------------------------------------

pandas/core/groupby.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1768,6 +1768,12 @@ def cumcount(self, ascending=True):
17681768
cumcounts = self._cumcount_array(ascending=ascending)
17691769
return Series(cumcounts, index)
17701770

1771+
@Substitution(name='groupby')
1772+
@Appender(_doc_template)
1773+
def rank(self, axis=0, *args, **kwargs):
1774+
"""Rank within each group"""
1775+
return self._cython_transform('rank', **kwargs)
1776+
17711777
@Substitution(name='groupby')
17721778
@Appender(_doc_template)
17731779
def cumprod(self, axis=0, *args, **kwargs):
@@ -2183,6 +2189,7 @@ def get_group_levels(self):
21832189
'cumsum': 'group_cumsum',
21842190
'cummin': 'group_cummin',
21852191
'cummax': 'group_cummax',
2192+
'rank': 'group_rank',
21862193
}
21872194
}
21882195

0 commit comments

Comments
 (0)