Skip to content

Commit 7784ec0

Browse files
committed
BUG: construct MultiIndex identically from levels/labels when concatting
closes pandas-dev#15622 closes pandas-dev#15687 closes pandas-dev#14015 closes pandas-dev#13431
1 parent 9d3554c commit 7784ec0

File tree

13 files changed

+375
-24
lines changed

13 files changed

+375
-24
lines changed

asv_bench/benchmarks/timeseries.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,10 @@ def setup(self):
292292
self.rng3 = date_range(start='1/1/2000', periods=1500000, freq='S')
293293
self.ts3 = Series(1, index=self.rng3)
294294

295-
def time_sort_index(self):
295+
def time_sort_index_monotonic(self):
296+
self.ts2.sort_index()
297+
298+
def time_sort_index_non_monotonic(self):
296299
self.ts.sort_index()
297300

298301
def time_timeseries_slice_minutely(self):

doc/source/whatsnew/v0.20.0.txt

+73-1
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,78 @@ If indicated, a deprecation warning will be issued if you reference that module.
656656
"pandas._hash", "pandas.tools.libhash", ""
657657
"pandas._window", "pandas.core.libwindow", ""
658658

659+
.. _whatsnew_0200.api_breaking.sort_index:
660+
661+
DataFrame.sort_index changes
662+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
663+
664+
In certain cases, calling ``.sort_index()`` on a MultiIndexed DataFrame would return the *same* DataFrame without seeming to sort.
665+
This would happen with a ``lexsorted``, but non-montonic levels. (:issue:`15622`, :issue:`15687`, :issue:`14015`, :issue:`13431`)
666+
667+
This is UNCHANGED between versions, but showing for illustration purposes:
668+
669+
.. ipython:: python
670+
671+
df = DataFrame(np.arange(6), columns=['value'], index=MultiIndex.from_product([list('BA'), range(3)]))
672+
df
673+
674+
.. ipython:: python
675+
676+
df.index.is_lexsorted()
677+
df.index.is_monotonic
678+
679+
Sorting works as expected
680+
681+
.. ipython:: python
682+
683+
df.sort_index()
684+
685+
.. ipython:: python
686+
687+
df.sort_index().index.is_lexsorted()
688+
df.sort_index().index.is_monotonic
689+
690+
However, this example, which has a monotonic level, doesn't behave as desired.
691+
692+
.. ipython:: python
693+
df = pd.DataFrame({'value': [1, 2, 3, 4]},
694+
index=pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],
695+
labels=[[0, 0, 1, 1], [0, 1, 0, 1]]))
696+
697+
Previous Behavior:
698+
699+
.. ipython:: python
700+
701+
In [11]: df.sort_index()
702+
Out[11]:
703+
value
704+
a bb 1
705+
aa 2
706+
b bb 3
707+
aa 4
708+
709+
In [14]: df.sort_index().index.is_lexsorted()
710+
Out[14]: True
711+
712+
In [15]: df.sort_index().index.is_monotonic
713+
Out[15]: False
714+
715+
New Behavior:
716+
717+
.. ipython:: python
718+
719+
df.sort_index()
720+
df.sort_index().index.is_lexsorted()
721+
df.sort_index().index.is_monotonic
722+
723+
Previous Behavior:
724+
725+
.. code-block:: ipython
726+
727+
New Behavior:
728+
729+
.. ipython:: python
730+
659731

660732
.. _whatsnew_0200.api_breaking.groupby_describe:
661733

@@ -830,7 +902,7 @@ Performance Improvements
830902
- Improved performance when using ``.unstack()`` (:issue:`15503`)
831903
- Improved performance of merge/join on ``category`` columns (:issue:`10409`)
832904
- Improved performance of ``drop_duplicates()`` on ``bool`` columns (:issue:`12963`)
833-
905+
- Improved performance of ``Series.sort_index()`` with a monotonic index (:issue:`15694`)
834906

835907
.. _whatsnew_0200.bug_fixes:
836908

pandas/core/frame.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -3308,6 +3308,10 @@ def trans(v):
33083308
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33093309
kind='quicksort', na_position='last', sort_remaining=True,
33103310
by=None):
3311+
3312+
# TODO: this can be combined with Series.sort_index impl as
3313+
# almost identical
3314+
33113315
inplace = validate_bool_kwarg(inplace, 'inplace')
33123316
# 10726
33133317
if by is not None:
@@ -3321,8 +3325,7 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33213325
axis = self._get_axis_number(axis)
33223326
labels = self._get_axis(axis)
33233327

3324-
# sort by the index
3325-
if level is not None:
3328+
if level:
33263329

33273330
new_axis, indexer = labels.sortlevel(level, ascending=ascending,
33283331
sort_remaining=sort_remaining)
@@ -3332,17 +3335,15 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33323335

33333336
# make sure that the axis is lexsorted to start
33343337
# if not we need to reconstruct to get the correct indexer
3335-
if not labels.is_lexsorted():
3336-
labels = MultiIndex.from_tuples(labels.values)
3338+
labels = labels._reconstruct(sort=True)
33373339

33383340
indexer = lexsort_indexer(labels.labels, orders=ascending,
33393341
na_position=na_position)
33403342
else:
33413343
from pandas.core.sorting import nargsort
33423344

3343-
# GH11080 - Check monotonic-ness before sort an index
3344-
# if monotonic (already sorted), return None or copy() according
3345-
# to 'inplace'
3345+
# Check monotonic-ness before sort an index
3346+
# GH11080
33463347
if ((ascending and labels.is_monotonic_increasing) or
33473348
(not ascending and labels.is_monotonic_decreasing)):
33483349
if inplace:
@@ -3353,8 +3354,9 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33533354
indexer = nargsort(labels, kind=kind, ascending=ascending,
33543355
na_position=na_position)
33553356

3357+
baxis = self._get_block_manager_axis(axis)
33563358
new_data = self._data.take(indexer,
3357-
axis=self._get_block_manager_axis(axis),
3359+
axis=baxis,
33583360
convert=False, verify=False)
33593361

33603362
if inplace:

pandas/core/groupby.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1808,6 +1808,13 @@ def get_group_levels(self):
18081808
'ohlc': lambda *args: ['open', 'high', 'low', 'close']
18091809
}
18101810

1811+
def _is_builtin_func(self, arg):
1812+
"""
1813+
if we define an builtin function for this argument, return it,
1814+
otherwise return the arg
1815+
"""
1816+
return SelectionMixin._builtin_table.get(arg, arg)
1817+
18111818
def _get_cython_function(self, kind, how, values, is_numeric):
18121819

18131820
dtype_str = values.dtype.name
@@ -2033,7 +2040,7 @@ def _aggregate_series_fast(self, obj, func):
20332040
# avoids object / Series creation overhead
20342041
dummy = obj._get_values(slice(None, 0)).to_dense()
20352042
indexer = get_group_index_sorter(group_index, ngroups)
2036-
obj = obj.take(indexer, convert=False)
2043+
obj = obj.take(indexer, convert=False).to_dense()
20372044
group_index = algorithms.take_nd(
20382045
group_index, indexer, allow_fill=False)
20392046
grouper = lib.SeriesGrouper(obj, func, group_index, ngroups,

pandas/core/reshape.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
from pandas.sparse.libsparse import IntIndex
2323

2424
from pandas.core.categorical import Categorical, _factorize_from_iterable
25-
from pandas.core.sorting import (get_group_index, compress_group_index,
26-
decons_obs_group_ids)
25+
from pandas.core.sorting import (get_group_index, get_compressed_ids,
26+
compress_group_index, decons_obs_group_ids)
2727

2828
import pandas.core.algorithms as algos
2929
from pandas._libs import algos as _algos, reshape as _reshape
@@ -494,11 +494,6 @@ def _unstack_frame(obj, level, fill_value=None):
494494
return unstacker.get_result()
495495

496496

497-
def get_compressed_ids(labels, sizes):
498-
ids = get_group_index(labels, sizes, sort=True, xnull=False)
499-
return compress_group_index(ids, sort=True)
500-
501-
502497
def stack(frame, level=-1, dropna=True):
503498
"""
504499
Convert DataFrame to Series with multi-level Index. Columns become the

pandas/core/series.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -1752,17 +1752,31 @@ def _try_kind_sort(arr):
17521752
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
17531753
kind='quicksort', na_position='last', sort_remaining=True):
17541754

1755+
# TODO: this can be combined with DataFrame.sort_index impl as
1756+
# almost identical
17551757
inplace = validate_bool_kwarg(inplace, 'inplace')
17561758
axis = self._get_axis_number(axis)
17571759
index = self.index
1758-
if level is not None:
1760+
1761+
if level:
17591762
new_index, indexer = index.sortlevel(level, ascending=ascending,
17601763
sort_remaining=sort_remaining)
17611764
elif isinstance(index, MultiIndex):
17621765
from pandas.core.sorting import lexsort_indexer
1763-
indexer = lexsort_indexer(index.labels, orders=ascending)
1766+
labels = index._reconstruct(sort=True)
1767+
indexer = lexsort_indexer(labels.labels, orders=ascending)
17641768
else:
17651769
from pandas.core.sorting import nargsort
1770+
1771+
# Check monotonic-ness before sort an index
1772+
# GH11080
1773+
if ((ascending and index.is_monotonic_increasing) or
1774+
(not ascending and index.is_monotonic_decreasing)):
1775+
if inplace:
1776+
return
1777+
else:
1778+
return self.copy()
1779+
17661780
indexer = nargsort(index, kind=kind, ascending=ascending,
17671781
na_position=na_position)
17681782

pandas/core/sorting.py

+5
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ def maybe_lift(lab, size): # pormote nan values
9393
return loop(list(labels), list(shape))
9494

9595

96+
def get_compressed_ids(labels, sizes):
97+
ids = get_group_index(labels, sizes, sort=True, xnull=False)
98+
return compress_group_index(ids, sort=True)
99+
100+
96101
def is_int64_overflow_possible(shape):
97102
the_prod = long(1)
98103
for x in shape:

pandas/indexes/multi.py

+50-2
Original file line numberDiff line numberDiff line change
@@ -1173,9 +1173,57 @@ def from_product(cls, iterables, sortorder=None, names=None):
11731173

11741174
labels, levels = _factorize_from_iterables(iterables)
11751175
labels = cartesian_product(labels)
1176+
return MultiIndex(levels, labels, sortorder=sortorder, names=names)
11761177

1177-
return MultiIndex(levels=levels, labels=labels, sortorder=sortorder,
1178-
names=names)
1178+
def _reconstruct(self, sort=False):
1179+
"""
1180+
reconstruct the MultiIndex
1181+
1182+
The MultiIndex will have the same outward appearance (e.g. values)
1183+
and will also .equals()
1184+
1185+
Parameters
1186+
----------
1187+
sort: boolean, default False
1188+
monotonically sort the levels
1189+
1190+
Returns
1191+
-------
1192+
MultiIndex
1193+
1194+
"""
1195+
new_levels = []
1196+
new_labels = []
1197+
1198+
if sort:
1199+
1200+
if self.is_monotonic:
1201+
return self
1202+
1203+
for lev, lab in zip(self.levels, self.labels):
1204+
1205+
if lev.is_monotonic:
1206+
new_levels.append(lev)
1207+
new_labels.append(lab)
1208+
continue
1209+
1210+
# indexer to reorder the levels
1211+
indexer = lev.argsort()
1212+
lev = lev.take(indexer)
1213+
1214+
# indexer to reorder the labels
1215+
ri = lib.get_reverse_indexer(indexer, len(indexer))
1216+
lab = algos.take_1d(ri, lab)
1217+
1218+
new_levels.append(lev)
1219+
new_labels.append(lab)
1220+
1221+
else:
1222+
return self
1223+
1224+
return MultiIndex(new_levels, new_labels,
1225+
names=self.names, sortorder=self.sortorder,
1226+
verify_integrity=False)
11791227

11801228
@property
11811229
def nlevels(self):

pandas/tests/indexes/test_multi.py

+53
Original file line numberDiff line numberDiff line change
@@ -2411,6 +2411,59 @@ def test_is_monotonic(self):
24112411

24122412
self.assertFalse(i.is_monotonic)
24132413

2414+
def test_reconstruct_sort(self):
2415+
2416+
# starts off lexsorted & monotonic
2417+
mi = MultiIndex.from_arrays([
2418+
['A', 'A', 'B', 'B', 'B'], [1, 2, 1, 2, 3]
2419+
])
2420+
assert mi.is_lexsorted()
2421+
assert mi.is_monotonic
2422+
2423+
recons = mi._reconstruct(sort=True)
2424+
assert recons.is_lexsorted()
2425+
assert recons.is_monotonic
2426+
assert mi is recons
2427+
2428+
assert mi.equals(recons)
2429+
assert Index(mi.values).equals(Index(recons.values))
2430+
2431+
recons = mi._reconstruct(sort=False)
2432+
assert recons.is_lexsorted()
2433+
assert recons.is_monotonic
2434+
assert mi is recons
2435+
2436+
assert mi.equals(recons)
2437+
assert Index(mi.values).equals(Index(recons.values))
2438+
2439+
# cannot convert to lexsorted
2440+
mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
2441+
('x', 'b'), ('y', 'a'), ('z', 'b')],
2442+
names=['one', 'two'])
2443+
assert not mi.is_lexsorted()
2444+
assert not mi.is_monotonic
2445+
2446+
recons = mi._reconstruct(sort=True)
2447+
assert not recons.is_lexsorted()
2448+
assert not recons.is_monotonic
2449+
2450+
assert mi.equals(recons)
2451+
assert Index(mi.values).equals(Index(recons.values))
2452+
2453+
# cannot convert to lexsorted
2454+
mi = MultiIndex(levels=[['b', 'd', 'a'], [1, 2, 3]],
2455+
labels=[[0, 1, 0, 2], [2, 0, 0, 1]],
2456+
names=['col1', 'col2'])
2457+
assert not mi.is_lexsorted()
2458+
assert not mi.is_monotonic
2459+
2460+
recons = mi._reconstruct(sort=True)
2461+
assert not recons.is_lexsorted()
2462+
assert not recons.is_monotonic
2463+
2464+
assert mi.equals(recons)
2465+
assert Index(mi.values).equals(Index(recons.values))
2466+
24142467
def test_isin(self):
24152468
values = [('foo', 2), ('bar', 3), ('quux', 4)]
24162469

pandas/tests/series/test_analytics.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1599,7 +1599,7 @@ def test_unstack(self):
15991599
labels=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]])
16001600
expected = DataFrame({'bar': s.values},
16011601
index=exp_index).sort_index(level=0)
1602-
unstacked = s.unstack(0)
1602+
unstacked = s.unstack(0).sort_index()
16031603
assert_frame_equal(unstacked, expected)
16041604

16051605
# GH5873

0 commit comments

Comments
 (0)