Skip to content

Commit 34ef9eb

Browse files
GuessWhoSamFoojreback
authored andcommitted
BUG: Series.rank modifies inplace with NaT (#18576)
1 parent 265e327 commit 34ef9eb

File tree

4 files changed

+26
-3
lines changed

4 files changed

+26
-3
lines changed

doc/source/whatsnew/v0.22.0.txt

+1-2
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ Reshaping
318318

319319
- Bug in :func:`DataFrame.stack` which fails trying to sort mixed type levels under Python 3 (:issue:`18310`)
320320
- Fixed construction of a :class:`Series` from a ``dict`` containing ``NaN`` as key (:issue:`18480`)
321-
321+
- Bug in :func:`Series.rank` where ``Series`` containing ``NaT`` modifies the ``Series`` inplace (:issue:`18521`)
322322
-
323323

324324
Numeric
@@ -339,4 +339,3 @@ Other
339339
^^^^^
340340

341341
- Improved error message when attempting to use a Python keyword as an identifier in a ``numexpr`` backed query (:issue:`18221`)
342-
-

pandas/_libs/algos_rank_helper.pxi.in

+5
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ def rank_1d_{{dtype}}(object in_arr, ties_method='average', ascending=True,
8484
mask = np.isnan(values)
8585
{{elif dtype == 'int64'}}
8686
mask = values == iNaT
87+
88+
# create copy in case of iNaT
89+
# values are mutated inplace
90+
if mask.any():
91+
values = values.copy()
8792
{{endif}}
8893

8994
# double sort first by mask and then by values to ensure nan values are

pandas/tests/frame/test_analytics.py

+9
Original file line numberDiff line numberDiff line change
@@ -2214,3 +2214,12 @@ def test_series_broadcasting(self):
22142214
df_nan.clip_lower(s, axis=0)
22152215
for op in ['lt', 'le', 'gt', 'ge', 'eq', 'ne']:
22162216
getattr(df, op)(s_nan, axis=0)
2217+
2218+
def test_series_nat_conversion(self):
2219+
# GH 18521
2220+
# Check rank does not mutate DataFrame
2221+
df = DataFrame(np.random.randn(10, 3), dtype='float64')
2222+
expected = df.copy()
2223+
df.rank()
2224+
result = df
2225+
tm.assert_frame_equal(result, expected)

pandas/tests/series/test_rank.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
from pandas import compat
2+
from pandas import compat, Timestamp
33

44
import pytest
55

@@ -368,3 +368,13 @@ def test_rank_object_bug(self):
368368
# smoke tests
369369
Series([np.nan] * 32).astype(object).rank(ascending=True)
370370
Series([np.nan] * 32).astype(object).rank(ascending=False)
371+
372+
def test_rank_modify_inplace(self):
373+
# GH 18521
374+
# Check rank does not mutate series
375+
s = Series([Timestamp('2017-01-05 10:20:27.569000'), NaT])
376+
expected = s.copy()
377+
378+
s.rank()
379+
result = s
380+
assert_series_equal(result, expected)

0 commit comments

Comments
 (0)