Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DEPR: deprecate sortlevel in favor of sort_index #15099

Merged
merged 1 commit into from
Jan 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions doc/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,6 @@ Reshaping, sorting
Series.reorder_levels
Series.sort_values
Series.sort_index
Series.sortlevel
Series.swaplevel
Series.unstack
Series.searchsorted
Expand Down Expand Up @@ -931,7 +930,6 @@ Reshaping, sorting, transposing
DataFrame.reorder_levels
DataFrame.sort_values
DataFrame.sort_index
DataFrame.sortlevel
DataFrame.nlargest
DataFrame.nsmallest
DataFrame.swaplevel
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ Deprecations
- ``Categorical.searchsorted()`` and ``Series.searchsorted()`` have deprecated the ``v`` parameter in favor of ``value`` (:issue:`12662`)
- ``TimedeltaIndex.searchsorted()``, ``DatetimeIndex.searchsorted()``, and ``PeriodIndex.searchsorted()`` have deprecated the ``key`` parameter in favor of ``value`` (:issue:`12662`)
- ``DataFrame.astype()`` has deprecated the ``raise_on_error`` parameter in favor of ``errors`` (:issue:`14878`)

- ``Series.sortlevel`` and ``DataFrame.sortlevel`` have been deprecated in favor of ``Series.sort_index`` and ``DataFrame.sort_index`` (:issue:`15099`)


.. _whatsnew_0200.prior_deprecations:
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,7 +1274,7 @@ def to_panel(self):

# minor axis must be sorted
if self.index.lexsort_depth < 2:
selfsorted = self.sortlevel(0)
selfsorted = self.sort_index(level=0)
else:
selfsorted = self

Expand Down Expand Up @@ -3337,6 +3337,8 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
def sortlevel(self, level=0, axis=0, ascending=True, inplace=False,
sort_remaining=True):
"""
DEPRECATED: use :meth:`DataFrame.sort_index`

Sort multilevel index by chosen axis and primary level. Data will be
lexicographically sorted by the chosen level followed by the other
levels (in order)
Expand All @@ -3360,6 +3362,8 @@ def sortlevel(self, level=0, axis=0, ascending=True, inplace=False,
DataFrame.sort_index(level=...)

"""
warnings.warn("sortlevel is deprecated, use sort_index(level= ...)",
FutureWarning, stacklevel=2)
return self.sort_index(level=level, axis=axis, ascending=ascending,
inplace=inplace, sort_remaining=sort_remaining)

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def pivot_simple(index, columns, values):

hindex = MultiIndex.from_arrays([index, columns])
series = Series(values.ravel(), index=hindex)
series = series.sortlevel(0)
series = series.sort_index(level=0)
return series.unstack()


Expand Down Expand Up @@ -596,7 +596,7 @@ def _convert_level_number(level_num, columns):
# which interferes with trying to sort based on the first
# level
level_to_sort = _convert_level_number(0, this.columns)
this = this.sortlevel(level_to_sort, axis=1)
this = this.sort_index(level=level_to_sort, axis=1)

# tuple list excluding level for grouping columns
if len(frame.columns.levels) > 2:
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1988,6 +1988,8 @@ def nsmallest(self, n=5, keep='first'):

def sortlevel(self, level=0, ascending=True, sort_remaining=True):
"""
DEPRECATED: use :meth:`Series.sort_index`

Sort Series with MultiIndex by chosen level. Data will be
lexicographically sorted by the chosen level followed by the other
levels (in order)
Expand All @@ -2006,6 +2008,8 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True):
Series.sort_index(level=...)

"""
warnings.warn("sortlevel is deprecated, use sort_index(level=...)",
FutureWarning, stacklevel=2)
return self.sort_index(level=level, ascending=ascending,
sort_remaining=sort_remaining)

Expand Down
2 changes: 1 addition & 1 deletion pandas/sparse/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ def stack_sparse_frame(frame):

lp = DataFrame(stacked_values.reshape((nobs, 1)), index=index,
columns=['foo'])
return lp.sortlevel(level=0)
return lp.sort_index(level=0)


def homogenize(series_dict):
Expand Down
2 changes: 1 addition & 1 deletion pandas/sparse/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,7 +947,7 @@ def setUp(self):
micol = pd.MultiIndex.from_product(
[['a', 'b', 'c'], ["1", "2"]], names=['col-foo', 'col-bar'])
dense_multiindex_frame = pd.DataFrame(
index=miindex, columns=micol).sortlevel().sortlevel(axis=1)
index=miindex, columns=micol).sort_index().sort_index(axis=1)
self.dense_multiindex_frame = dense_multiindex_frame.fillna(value=3.14)

def test_to_sparse_preserve_multiindex_names_columns(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/stats/plm.py
Original file line number Diff line number Diff line change
Expand Up @@ -792,8 +792,8 @@ def _var_beta_panel(y, x, beta, xx, rmse, cluster_axis,
resid = DataFrame(yv[:, None] - Xb, index=y.index, columns=['resid'])

if cluster_axis == 1:
x = x.swaplevel(0, 1).sortlevel(0)
resid = resid.swaplevel(0, 1).sortlevel(0)
x = x.swaplevel(0, 1).sort_index(level=0)
resid = resid.swaplevel(0, 1).sort_index(level=0)

m = _group_agg(x.values * resid.values, x.index._bounds,
lambda x: np.sum(x, axis=0))
Expand Down
4 changes: 0 additions & 4 deletions pandas/tests/frame/test_misc_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,10 +456,6 @@ def _check_f(base, f):
f = lambda x: x.sort_index(inplace=True)
_check_f(data.copy(), f)

# sortlevel
f = lambda x: x.sortlevel(0, inplace=True)
_check_f(data.set_index(['a', 'b']), f)

# fillna
f = lambda x: x.fillna(0, inplace=True)
_check_f(data.copy(), f)
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/frame/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def test_binary_ops_align(self):

df = DataFrame(np.arange(27 * 3).reshape(27, 3),
index=index,
columns=['value1', 'value2', 'value3']).sortlevel()
columns=['value1', 'value2', 'value3']).sort_index()

idx = pd.IndexSlice
for op in ['add', 'sub', 'mul', 'div', 'truediv']:
Expand All @@ -479,15 +479,15 @@ def test_binary_ops_align(self):
result = getattr(df, op)(x, level='third', axis=0)

expected = pd.concat([opa(df.loc[idx[:, :, i], :], v)
for i, v in x.iteritems()]).sortlevel()
for i, v in x.iteritems()]).sort_index()
assert_frame_equal(result, expected)

x = Series([1.0, 10.0], ['two', 'three'])
result = getattr(df, op)(x, level='second', axis=0)

expected = (pd.concat([opa(df.loc[idx[:, i], :], v)
for i, v in x.iteritems()])
.reindex_like(df).sortlevel())
.reindex_like(df).sort_index())
assert_frame_equal(result, expected)

# GH9463 (alignment level of dataframe with series)
Expand Down
18 changes: 5 additions & 13 deletions pandas/tests/frame/test_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,6 @@ def test_sort_index_multiindex(self):
mi = MultiIndex.from_tuples([[2, 1, 3], [1, 1, 1]], names=list('ABC'))
df = DataFrame([[1, 2], [3, 4]], mi)

result = df.sort_index(level='A', sort_remaining=False)
expected = df.sortlevel('A', sort_remaining=False)
assert_frame_equal(result, expected)

# sort columns by specified level of multi-index
df = df.T
result = df.sort_index(level='A', axis=1, sort_remaining=False)
expected = df.sortlevel('A', axis=1, sort_remaining=False)
assert_frame_equal(result, expected)

# MI sort, but no level: sort_level has no effect
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC'))
df = DataFrame([[1, 2], [3, 4]], mi)
Expand All @@ -79,6 +69,8 @@ def test_sort(self):
frame.sort(columns='A')
with tm.assert_produces_warning(FutureWarning):
frame.sort()
with tm.assert_produces_warning(FutureWarning):
frame.sortlevel()

def test_sort_values(self):
frame = DataFrame([[1, 1, 2], [3, 1, 0], [4, 5, 6]],
Expand Down Expand Up @@ -453,13 +445,13 @@ def test_sort_index_duplicates(self):
result = df.sort_values(by=('a', 1))
assert_frame_equal(result, expected)

def test_sortlevel(self):
def test_sort_index_level(self):
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC'))
df = DataFrame([[1, 2], [3, 4]], mi)
res = df.sortlevel('A', sort_remaining=False)
res = df.sort_index(level='A', sort_remaining=False)
assert_frame_equal(df, res)

res = df.sortlevel(['A', 'B'], sort_remaining=False)
res = df.sort_index(level=['A', 'B'], sort_remaining=False)
assert_frame_equal(df, res)

def test_sort_datetimes(self):
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -3427,7 +3427,7 @@ def test_int64_overflow(self):
left = lg.sum()['values']
right = rg.sum()['values']

exp_index, _ = left.index.sortlevel(0)
exp_index, _ = left.index.sortlevel()
self.assert_index_equal(left.index, exp_index)

exp_index, _ = right.index.sortlevel(0)
Expand Down Expand Up @@ -3708,7 +3708,7 @@ def test_more_flexible_frame_multi_function(self):
exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]]))

expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1)
expected = expected.swaplevel(0, 1, axis=1).sortlevel(0, axis=1)
expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1)

d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]])
result = grouped.aggregate(d)
Expand Down Expand Up @@ -4711,7 +4711,7 @@ def test_timegrouper_with_reg_groups(self):
expected = df.groupby('user_id')[
'whole_cost'].resample(
freq).sum().dropna().reorder_levels(
['date', 'user_id']).sortlevel().astype('int64')
['date', 'user_id']).sort_index().astype('int64')
expected.name = 'whole_cost'

result1 = df.sort_index().groupby([pd.TimeGrouper(freq=freq),
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ def test_set_value_keeps_names(self):
np.random.randn(6, 4),
columns=['one', 'two', 'three', 'four'],
index=idx)
df = df.sortlevel()
df = df.sort_index()
self.assertIsNone(df.is_copy)
self.assertEqual(df.index.names, ('Name', 'Number'))
df = df.set_value(('grethe', '4'), 'one', 99.34)
Expand Down
32 changes: 16 additions & 16 deletions pandas/tests/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2104,7 +2104,7 @@ def test_ix_general(self):
tm.assert_frame_equal(df.ix[key], df.iloc[2:])

# this is ok
df.sortlevel(inplace=True)
df.sort_index(inplace=True)
res = df.ix[key]
# col has float dtype, result should be Float64Index
index = MultiIndex.from_arrays([[4.] * 3, [2012] * 3],
Expand Down Expand Up @@ -2137,7 +2137,7 @@ def test_xs_multiindex(self):
[('a', 'foo'), ('a', 'bar'), ('b', 'hello'),
('b', 'world')], names=['lvl0', 'lvl1'])
df = DataFrame(np.random.randn(4, 4), columns=columns)
df.sortlevel(axis=1, inplace=True)
df.sort_index(axis=1, inplace=True)
result = df.xs('a', level='lvl0', axis=1)
expected = df.iloc[:, 0:2].loc[:, 'a']
tm.assert_frame_equal(result, expected)
Expand Down Expand Up @@ -2180,7 +2180,7 @@ def test_per_axis_per_level_getitem(self):
df = DataFrame(
np.arange(16, dtype='int64').reshape(
4, 4), index=index, columns=columns)
df = df.sortlevel(axis=0).sortlevel(axis=1)
df = df.sort_index(axis=0).sort_index(axis=1)

# identity
result = df.loc[(slice(None), slice(None)), :]
Expand Down Expand Up @@ -2249,7 +2249,7 @@ def f():

# not lexsorted
self.assertEqual(df.index.lexsort_depth, 2)
df = df.sortlevel(level=1, axis=0)
df = df.sort_index(level=1, axis=0)
self.assertEqual(df.index.lexsort_depth, 0)
with tm.assertRaisesRegexp(
UnsortedIndexError,
Expand All @@ -2265,11 +2265,11 @@ def test_multiindex_slicers_non_unique(self):
B=['a', 'a', 'a', 'a'],
C=[1, 2, 1, 3],
D=[1, 2, 3, 4]))
.set_index(['A', 'B', 'C']).sortlevel())
.set_index(['A', 'B', 'C']).sort_index())
self.assertFalse(df.index.is_unique)
expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'],
C=[1, 1], D=[1, 3]))
.set_index(['A', 'B', 'C']).sortlevel())
.set_index(['A', 'B', 'C']).sort_index())
result = df.loc[(slice(None), slice(None), 1), :]
tm.assert_frame_equal(result, expected)

Expand All @@ -2281,11 +2281,11 @@ def test_multiindex_slicers_non_unique(self):
B=['a', 'a', 'a', 'a'],
C=[1, 2, 1, 2],
D=[1, 2, 3, 4]))
.set_index(['A', 'B', 'C']).sortlevel())
.set_index(['A', 'B', 'C']).sort_index())
self.assertFalse(df.index.is_unique)
expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'],
C=[1, 1], D=[1, 3]))
.set_index(['A', 'B', 'C']).sortlevel())
.set_index(['A', 'B', 'C']).sort_index())
result = df.loc[(slice(None), slice(None), 1), :]
self.assertFalse(result.index.is_unique)
tm.assert_frame_equal(result, expected)
Expand Down Expand Up @@ -2357,7 +2357,7 @@ def test_multiindex_slicers_edges(self):

df['DATE'] = pd.to_datetime(df['DATE'])
df1 = df.set_index(['A', 'B', 'DATE'])
df1 = df1.sortlevel()
df1 = df1.sort_index()

# A1 - Get all values under "A0" and "A1"
result = df1.loc[(slice('A1')), :]
Expand Down Expand Up @@ -2440,7 +2440,7 @@ def f():
df.loc['A1', (slice(None), 'foo')]

self.assertRaises(UnsortedIndexError, f)
df = df.sortlevel(axis=1)
df = df.sort_index(axis=1)

# slicing
df.loc['A1', (slice(None), 'foo')]
Expand All @@ -2459,7 +2459,7 @@ def test_loc_axis_arguments(self):
df = DataFrame(np.arange(len(index) * len(columns), dtype='int64')
.reshape((len(index), len(columns))),
index=index,
columns=columns).sortlevel().sortlevel(axis=1)
columns=columns).sort_index().sort_index(axis=1)

# axis 0
result = df.loc(axis=0)['A1':'A3', :, ['C1', 'C3']]
Expand Down Expand Up @@ -2551,7 +2551,7 @@ def test_per_axis_per_level_setitem(self):
df_orig = DataFrame(
np.arange(16, dtype='int64').reshape(
4, 4), index=index, columns=columns)
df_orig = df_orig.sortlevel(axis=0).sortlevel(axis=1)
df_orig = df_orig.sort_index(axis=0).sort_index(axis=1)

# identity
df = df_orig.copy()
Expand Down Expand Up @@ -2764,12 +2764,12 @@ def f():
idx = pd.MultiIndex.from_product([['A', 'B', 'C'],
['foo', 'bar', 'baz']],
names=['one', 'two'])
s = pd.Series(np.arange(9, dtype='int64'), index=idx).sortlevel()
s = pd.Series(np.arange(9, dtype='int64'), index=idx).sort_index()

exp_idx = pd.MultiIndex.from_product([['A'], ['foo', 'bar', 'baz']],
names=['one', 'two'])
expected = pd.Series(np.arange(3, dtype='int64'),
index=exp_idx).sortlevel()
index=exp_idx).sort_index()

result = s.loc[['A']]
tm.assert_series_equal(result, expected)
Expand All @@ -2786,7 +2786,7 @@ def f():

idx = pd.IndexSlice
expected = pd.Series([0, 3, 6], index=pd.MultiIndex.from_product(
[['A', 'B', 'C'], ['foo']], names=['one', 'two'])).sortlevel()
[['A', 'B', 'C'], ['foo']], names=['one', 'two'])).sort_index()

result = s.loc[idx[:, ['foo']]]
tm.assert_series_equal(result, expected)
Expand All @@ -2799,7 +2799,7 @@ def f():
['alpha', 'beta']))
df = DataFrame(
np.random.randn(5, 6), index=range(5), columns=multi_index)
df = df.sortlevel(0, axis=1)
df = df.sort_index(level=0, axis=1)

expected = DataFrame(index=range(5),
columns=multi_index.reindex([])[0])
Expand Down
Loading