Skip to content

Commit dfd1549

Browse files
committed
Initial working rank with no tiebreaker
1 parent 12ac43f commit dfd1549

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

pandas/_libs/groupby_helper.pxi.in

+33
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

+7
Original file line numberDiff line numberDiff line change
@@ -1756,6 +1756,12 @@ def cumcount(self, ascending=True):
17561756
cumcounts = self._cumcount_array(ascending=ascending)
17571757
return Series(cumcounts, index)
17581758

1759+
@Substitution(name='groupby')
1760+
@Appender(_doc_template)
1761+
def rank(self, axis=0, *args, **kwargs):
1762+
"""Rank within each group"""
1763+
return self._cython_transform('rank', **kwargs)
1764+
17591765
@Substitution(name='groupby')
17601766
@Appender(_doc_template)
17611767
def cumprod(self, axis=0, *args, **kwargs):
@@ -2171,6 +2177,7 @@ def get_group_levels(self):
21712177
'cumsum': 'group_cumsum',
21722178
'cummin': 'group_cummin',
21732179
'cummax': 'group_cummax',
2180+
'rank': 'group_rank',
21742181
}
21752182
}
21762183

0 commit comments

Comments
 (0)