Skip to content

Commit 08d7b2c

Browse files
gfyoungjorisvandenbossche
authored andcommitted
Standardize function signatures (#14645)
Standardize the following function signatures: 1) repeat(reps, *args, **kwargs) 2) searchsorted(value, side='left', sorter=None) Closes gh-12662.
1 parent 6d2b34a commit 08d7b2c

File tree

14 files changed

+103
-49
lines changed

14 files changed

+103
-49
lines changed

doc/source/whatsnew/v0.20.0.txt

+4
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ Other API Changes
6363
Deprecations
6464
^^^^^^^^^^^^
6565

66+
- ``Series.repeat()`` has deprecated the ``reps`` parameter in favor of ``repeats`` (:issue:`12662`)
67+
- ``Index.repeat()`` and ``MultiIndex.repeat()`` have deprecated the ``n`` parameter in favor of ``repeats`` (:issue:`12662`)
68+
- ``Categorical.searchsorted()`` and ``Series.searchsorted()`` have deprecated the ``v`` parameter in favor of ``value`` (:issue:`12662`)
69+
- ``TimedeltaIndex.searchsorted()``, ``DatetimeIndex.searchsorted()``, and ``PeriodIndex.searchsorted()`` have deprecated the ``key`` parameter in favor of ``value`` (:issue:`12662`)
6670

6771

6872

pandas/core/base.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -1091,12 +1091,12 @@ def factorize(self, sort=False, na_sentinel=-1):
10911091
"""Find indices where elements should be inserted to maintain order.
10921092
10931093
Find the indices into a sorted %(klass)s `self` such that, if the
1094-
corresponding elements in `v` were inserted before the indices, the
1095-
order of `self` would be preserved.
1094+
corresponding elements in `value` were inserted before the indices,
1095+
the order of `self` would be preserved.
10961096
10971097
Parameters
10981098
----------
1099-
%(value)s : array_like
1099+
value : array_like
11001100
Values to insert into `self`.
11011101
side : {'left', 'right'}, optional
11021102
If 'left', the index of the first suitable location found is given.
@@ -1109,7 +1109,7 @@ def factorize(self, sort=False, na_sentinel=-1):
11091109
Returns
11101110
-------
11111111
indices : array of ints
1112-
Array of insertion points with the same shape as `v`.
1112+
Array of insertion points with the same shape as `value`.
11131113
11141114
See Also
11151115
--------
@@ -1149,11 +1149,12 @@ def factorize(self, sort=False, na_sentinel=-1):
11491149
array([3, 4]) # eggs before milk
11501150
""")
11511151

1152-
@Substitution(klass='IndexOpsMixin', value='key')
1152+
@Substitution(klass='IndexOpsMixin')
11531153
@Appender(_shared_docs['searchsorted'])
1154-
def searchsorted(self, key, side='left', sorter=None):
1154+
@deprecate_kwarg(old_arg_name='key', new_arg_name='value')
1155+
def searchsorted(self, value, side='left', sorter=None):
11551156
# needs coercion on the key (DatetimeIndex does already)
1156-
return self.values.searchsorted(key, side=side, sorter=sorter)
1157+
return self.values.searchsorted(value, side=side, sorter=sorter)
11571158

11581159
_shared_docs['drop_duplicates'] = (
11591160
"""Return %(klass)s with duplicate values removed

pandas/core/categorical.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1076,17 +1076,18 @@ def memory_usage(self, deep=False):
10761076
"""
10771077
return self._codes.nbytes + self._categories.memory_usage(deep=deep)
10781078

1079-
@Substitution(klass='Categorical', value='v')
1079+
@Substitution(klass='Categorical')
10801080
@Appender(_shared_docs['searchsorted'])
1081-
def searchsorted(self, v, side='left', sorter=None):
1081+
@deprecate_kwarg(old_arg_name='v', new_arg_name='value')
1082+
def searchsorted(self, value, side='left', sorter=None):
10821083
if not self.ordered:
10831084
raise ValueError("Categorical not ordered\nyou can use "
10841085
".as_ordered() to change the Categorical to an "
10851086
"ordered one")
10861087

10871088
from pandas.core.series import Series
10881089
values_as_codes = self.categories.values.searchsorted(
1089-
Series(v).values, side=side)
1090+
Series(value).values, side=side)
10901091

10911092
return self.codes.searchsorted(values_as_codes, sorter=sorter)
10921093

pandas/core/series.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -832,18 +832,19 @@ def _set_values(self, key, value):
832832
self._data = self._data.setitem(indexer=key, value=value)
833833
self._maybe_update_cacher()
834834

835-
def repeat(self, reps, *args, **kwargs):
835+
@deprecate_kwarg(old_arg_name='reps', new_arg_name='repeats')
836+
def repeat(self, repeats, *args, **kwargs):
836837
"""
837838
Repeat elements of an Series. Refer to `numpy.ndarray.repeat`
838-
for more information about the `reps` argument.
839+
for more information about the `repeats` argument.
839840
840841
See also
841842
--------
842843
numpy.ndarray.repeat
843844
"""
844845
nv.validate_repeat(args, kwargs)
845-
new_index = self.index.repeat(reps)
846-
new_values = self._values.repeat(reps)
846+
new_index = self.index.repeat(repeats)
847+
new_values = self._values.repeat(repeats)
847848
return self._constructor(new_values,
848849
index=new_index).__finalize__(self)
849850

@@ -1509,12 +1510,13 @@ def dot(self, other):
15091510
else: # pragma: no cover
15101511
raise TypeError('unsupported type: %s' % type(other))
15111512

1512-
@Substitution(klass='Series', value='v')
1513+
@Substitution(klass='Series')
15131514
@Appender(base._shared_docs['searchsorted'])
1514-
def searchsorted(self, v, side='left', sorter=None):
1515+
@deprecate_kwarg(old_arg_name='v', new_arg_name='value')
1516+
def searchsorted(self, value, side='left', sorter=None):
15151517
if sorter is not None:
15161518
sorter = _ensure_platform_int(sorter)
1517-
return self._values.searchsorted(Series(v)._values,
1519+
return self._values.searchsorted(Series(value)._values,
15181520
side=side, sorter=sorter)
15191521

15201522
# -------------------------------------------------------------------

pandas/indexes/base.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -535,17 +535,18 @@ def tolist(self):
535535
"""
536536
return list(self.values)
537537

538-
def repeat(self, n, *args, **kwargs):
538+
@deprecate_kwarg(old_arg_name='n', new_arg_name='repeats')
539+
def repeat(self, repeats, *args, **kwargs):
539540
"""
540541
Repeat elements of an Index. Refer to `numpy.ndarray.repeat`
541-
for more information about the `n` argument.
542+
for more information about the `repeats` argument.
542543
543544
See also
544545
--------
545546
numpy.ndarray.repeat
546547
"""
547548
nv.validate_repeat(args, kwargs)
548-
return self._shallow_copy(self._values.repeat(n))
549+
return self._shallow_copy(self._values.repeat(repeats))
549550

550551
def where(self, cond, other=None):
551552
"""

pandas/indexes/multi.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1166,10 +1166,11 @@ def append(self, other):
11661166
def argsort(self, *args, **kwargs):
11671167
return self.values.argsort(*args, **kwargs)
11681168

1169-
def repeat(self, n, *args, **kwargs):
1169+
@deprecate_kwarg(old_arg_name='n', new_arg_name='repeats')
1170+
def repeat(self, repeats, *args, **kwargs):
11701171
nv.validate_repeat(args, kwargs)
11711172
return MultiIndex(levels=self.levels,
1172-
labels=[label.view(np.ndarray).repeat(n)
1173+
labels=[label.view(np.ndarray).repeat(repeats)
11731174
for label in self.labels], names=self.names,
11741175
sortorder=self.sortorder, verify_integrity=False)
11751176

pandas/tests/indexes/test_base.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
Float64Index, Int64Index,
1818
CategoricalIndex, DatetimeIndex, TimedeltaIndex,
1919
PeriodIndex)
20+
from pandas.core.index import _get_combined_index
2021
from pandas.util.testing import assert_almost_equal
2122
from pandas.compat.numpy import np_datetime64_compat
2223

@@ -1976,8 +1977,18 @@ def test_dropna(self):
19761977
with tm.assertRaisesRegexp(ValueError, msg):
19771978
pd.Index([1, 2, 3]).dropna(how='xxx')
19781979

1980+
def test_get_combined_index(self):
1981+
result = _get_combined_index([])
1982+
tm.assert_index_equal(result, Index([]))
19791983

1980-
def test_get_combined_index():
1981-
from pandas.core.index import _get_combined_index
1982-
result = _get_combined_index([])
1983-
tm.assert_index_equal(result, Index([]))
1984+
def test_repeat(self):
1985+
repeats = 2
1986+
idx = pd.Index([1, 2, 3])
1987+
expected = pd.Index([1, 1, 2, 2, 3, 3])
1988+
1989+
result = idx.repeat(repeats)
1990+
tm.assert_index_equal(result, expected)
1991+
1992+
with tm.assert_produces_warning(FutureWarning):
1993+
result = idx.repeat(n=repeats)
1994+
tm.assert_index_equal(result, expected)

pandas/tests/indexes/test_multi.py

+4
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ def test_repeat(self):
9797
numbers, names.repeat(reps)], names=names)
9898
tm.assert_index_equal(m.repeat(reps), expected)
9999

100+
with tm.assert_produces_warning(FutureWarning):
101+
result = m.repeat(n=reps)
102+
tm.assert_index_equal(result, expected)
103+
100104
def test_numpy_repeat(self):
101105
reps = 2
102106
numbers = [1, 2, 3]

pandas/tests/series/test_analytics.py

+17
Original file line numberDiff line numberDiff line change
@@ -1363,6 +1363,10 @@ def test_repeat(self):
13631363
exp = Series(s.values.repeat(5), index=s.index.values.repeat(5))
13641364
assert_series_equal(reps, exp)
13651365

1366+
with tm.assert_produces_warning(FutureWarning):
1367+
result = s.repeat(reps=5)
1368+
assert_series_equal(result, exp)
1369+
13661370
to_rep = [2, 3, 4]
13671371
reps = s.repeat(to_rep)
13681372
exp = Series(s.values.repeat(to_rep),
@@ -1378,6 +1382,19 @@ def test_numpy_repeat(self):
13781382
msg = "the 'axis' parameter is not supported"
13791383
tm.assertRaisesRegexp(ValueError, msg, np.repeat, s, 2, axis=0)
13801384

1385+
def test_searchsorted(self):
1386+
s = Series([1, 2, 3])
1387+
1388+
idx = s.searchsorted(1, side='left')
1389+
tm.assert_numpy_array_equal(idx, np.array([0], dtype=np.intp))
1390+
1391+
idx = s.searchsorted(1, side='right')
1392+
tm.assert_numpy_array_equal(idx, np.array([1], dtype=np.intp))
1393+
1394+
with tm.assert_produces_warning(FutureWarning):
1395+
idx = s.searchsorted(v=1, side='left')
1396+
tm.assert_numpy_array_equal(idx, np.array([0], dtype=np.intp))
1397+
13811398
def test_searchsorted_numeric_dtypes_scalar(self):
13821399
s = Series([1, 2, 90, 1000, 3e9])
13831400
r = s.searchsorted(30)

pandas/tests/test_categorical.py

+5
Original file line numberDiff line numberDiff line change
@@ -1593,6 +1593,11 @@ def test_searchsorted(self):
15931593
self.assert_numpy_array_equal(res, exp)
15941594
self.assert_numpy_array_equal(res, chk)
15951595

1596+
with tm.assert_produces_warning(FutureWarning):
1597+
res = c1.searchsorted(v=['bread'])
1598+
exp = np.array([1], dtype=np.intp)
1599+
tm.assert_numpy_array_equal(res, exp)
1600+
15961601
def test_deprecated_labels(self):
15971602
# TODO: labels is deprecated and should be removed in 0.18 or 2017,
15981603
# whatever is earlier

pandas/tseries/index.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -1620,15 +1620,16 @@ def normalize(self):
16201620
return DatetimeIndex(new_values, freq='infer', name=self.name,
16211621
tz=self.tz)
16221622

1623-
@Substitution(klass='DatetimeIndex', value='key')
1623+
@Substitution(klass='DatetimeIndex')
16241624
@Appender(_shared_docs['searchsorted'])
1625-
def searchsorted(self, key, side='left', sorter=None):
1626-
if isinstance(key, (np.ndarray, Index)):
1627-
key = np.array(key, dtype=_NS_DTYPE, copy=False)
1625+
@deprecate_kwarg(old_arg_name='key', new_arg_name='value')
1626+
def searchsorted(self, value, side='left', sorter=None):
1627+
if isinstance(value, (np.ndarray, Index)):
1628+
value = np.array(value, dtype=_NS_DTYPE, copy=False)
16281629
else:
1629-
key = _to_m8(key, tz=self.tz)
1630+
value = _to_m8(value, tz=self.tz)
16301631

1631-
return self.values.searchsorted(key, side=side)
1632+
return self.values.searchsorted(value, side=side)
16321633

16331634
def is_type_compatible(self, typ):
16341635
return typ == self.inferred_type or typ == 'datetime'

pandas/tseries/period.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@
3939
from pandas.indexes.base import _index_shared_docs, _ensure_index
4040

4141
from pandas import compat
42-
from pandas.util.decorators import Appender, cache_readonly, Substitution
42+
from pandas.util.decorators import (Appender, Substitution, cache_readonly,
43+
deprecate_kwarg)
4344
from pandas.lib import infer_dtype
4445
import pandas.tslib as tslib
4546
from pandas.compat import zip, u
@@ -460,18 +461,19 @@ def astype(self, dtype, copy=True, how='start'):
460461
return self.asfreq(freq=dtype.freq)
461462
raise ValueError('Cannot cast PeriodIndex to dtype %s' % dtype)
462463

463-
@Substitution(klass='PeriodIndex', value='key')
464+
@Substitution(klass='PeriodIndex')
464465
@Appender(_shared_docs['searchsorted'])
465-
def searchsorted(self, key, side='left', sorter=None):
466-
if isinstance(key, Period):
467-
if key.freq != self.freq:
468-
msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, key.freqstr)
466+
@deprecate_kwarg(old_arg_name='key', new_arg_name='value')
467+
def searchsorted(self, value, side='left', sorter=None):
468+
if isinstance(value, Period):
469+
if value.freq != self.freq:
470+
msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr)
469471
raise IncompatibleFrequency(msg)
470-
key = key.ordinal
471-
elif isinstance(key, compat.string_types):
472-
key = Period(key, freq=self.freq).ordinal
472+
value = value.ordinal
473+
elif isinstance(value, compat.string_types):
474+
value = Period(value, freq=self.freq).ordinal
473475

474-
return self._values.searchsorted(key, side=side, sorter=sorter)
476+
return self._values.searchsorted(value, side=side, sorter=sorter)
475477

476478
@property
477479
def is_all_dates(self):

pandas/tseries/tdi.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from pandas.indexes.base import _index_shared_docs
2626
import pandas.core.common as com
2727
import pandas.types.concat as _concat
28-
from pandas.util.decorators import Appender, Substitution
28+
from pandas.util.decorators import Appender, Substitution, deprecate_kwarg
2929
from pandas.tseries.base import TimelikeOps, DatetimeIndexOpsMixin
3030
from pandas.tseries.timedeltas import (to_timedelta,
3131
_coerce_scalar_to_timedelta_type)
@@ -785,15 +785,16 @@ def _partial_td_slice(self, key, freq, use_lhs=True, use_rhs=True):
785785
# # try to find a the dates
786786
# return (lhs_mask & rhs_mask).nonzero()[0]
787787

788-
@Substitution(klass='TimedeltaIndex', value='key')
788+
@Substitution(klass='TimedeltaIndex')
789789
@Appender(_shared_docs['searchsorted'])
790-
def searchsorted(self, key, side='left', sorter=None):
791-
if isinstance(key, (np.ndarray, Index)):
792-
key = np.array(key, dtype=_TD_DTYPE, copy=False)
790+
@deprecate_kwarg(old_arg_name='key', new_arg_name='value')
791+
def searchsorted(self, value, side='left', sorter=None):
792+
if isinstance(value, (np.ndarray, Index)):
793+
value = np.array(value, dtype=_TD_DTYPE, copy=False)
793794
else:
794-
key = _to_m8(key)
795+
value = _to_m8(value)
795796

796-
return self.values.searchsorted(key, side=side, sorter=sorter)
797+
return self.values.searchsorted(value, side=side, sorter=sorter)
797798

798799
def is_type_compatible(self, typ):
799800
return typ == self.inferred_type or typ == 'timedelta'

pandas/tseries/tests/test_period.py

+3
Original file line numberDiff line numberDiff line change
@@ -3698,6 +3698,9 @@ def test_searchsorted(self):
36983698
with self.assertRaisesRegexp(period.IncompatibleFrequency, msg):
36993699
pidx.searchsorted(pd.Period('2014-01-01', freq='5D'))
37003700

3701+
with tm.assert_produces_warning(FutureWarning):
3702+
pidx.searchsorted(key=p2)
3703+
37013704
def test_round_trip(self):
37023705

37033706
p = Period('2000Q1')

0 commit comments

Comments
 (0)