Skip to content

Commit 685dadc

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 37e5f78 commit 685dadc

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
@@ -623,6 +623,78 @@ If indicated, a deprecation warning will be issued if you reference that module.
623623
"pandas._hash", "pandas.tools.libhash", ""
624624
"pandas._window", "pandas.core.libwindow", ""
625625

626+
.. _whatsnew_0200.api_breaking.sort_index:
627+
628+
DataFrame.sort_index changes
629+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
630+
631+
In certain cases, calling ``.sort_index()`` on a MultiIndexed DataFrame would return the *same* DataFrame without seeming to sort.
632+
This would happen with a ``lexsorted``, but non-montonic levels. (:issue:`15622`, :issue:`15687`, :issue:`14015`, :issue:`13431`)
633+
634+
This is UNCHANGED between versions, but showing for illustration purposes:
635+
636+
.. ipython:: python
637+
638+
df = DataFrame(np.arange(6), columns=['value'], index=MultiIndex.from_product([list('BA'), range(3)]))
639+
df
640+
641+
.. ipython:: python
642+
643+
df.index.is_lexsorted()
644+
df.index.is_monotonic
645+
646+
Sorting works as expected
647+
648+
.. ipython:: python
649+
650+
df.sort_index()
651+
652+
.. ipython:: python
653+
654+
df.sort_index().index.is_lexsorted()
655+
df.sort_index().index.is_monotonic
656+
657+
However, this example, which has a monotonic level, doesn't behave as desired.
658+
659+
.. ipython:: python
660+
df = pd.DataFrame({'value': [1, 2, 3, 4]},
661+
index=pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],
662+
labels=[[0, 0, 1, 1], [0, 1, 0, 1]]))
663+
664+
Previous Behavior:
665+
666+
.. ipython:: python
667+
668+
In [11]: df.sort_index()
669+
Out[11]:
670+
value
671+
a bb 1
672+
aa 2
673+
b bb 3
674+
aa 4
675+
676+
In [14]: df.sort_index().index.is_lexsorted()
677+
Out[14]: True
678+
679+
In [15]: df.sort_index().index.is_monotonic
680+
Out[15]: False
681+
682+
New Behavior:
683+
684+
.. ipython:: python
685+
686+
df.sort_index()
687+
df.sort_index().index.is_lexsorted()
688+
df.sort_index().index.is_monotonic
689+
690+
Previous Behavior:
691+
692+
.. code-block:: ipython
693+
694+
New Behavior:
695+
696+
.. ipython:: python
697+
626698

627699
.. _whatsnew_0200.api_breaking.groupby_describe:
628700

@@ -785,7 +857,7 @@ Performance Improvements
785857
- Improved performance of ``.rank()`` for categorical data (:issue:`15498`)
786858
- Improved performance when using ``.unstack()`` (:issue:`15503`)
787859
- Improved performance of merge/join on ``category`` columns (:issue:`10409`)
788-
860+
- Improved performance of ``Series.sort_index()`` with a monotonic index (:issue:`15694`)
789861

790862
.. _whatsnew_0200.bug_fixes:
791863

pandas/core/frame.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -3365,6 +3365,10 @@ def sort(self, columns=None, axis=0, ascending=True, inplace=False,
33653365
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33663366
kind='quicksort', na_position='last', sort_remaining=True,
33673367
by=None):
3368+
3369+
# TODO: this can be combined with Series.sort_index impl as
3370+
# almost identical
3371+
33683372
inplace = validate_bool_kwarg(inplace, 'inplace')
33693373
# 10726
33703374
if by is not None:
@@ -3378,8 +3382,7 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33783382
axis = self._get_axis_number(axis)
33793383
labels = self._get_axis(axis)
33803384

3381-
# sort by the index
3382-
if level is not None:
3385+
if level:
33833386

33843387
new_axis, indexer = labels.sortlevel(level, ascending=ascending,
33853388
sort_remaining=sort_remaining)
@@ -3389,17 +3392,15 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
33893392

33903393
# make sure that the axis is lexsorted to start
33913394
# if not we need to reconstruct to get the correct indexer
3392-
if not labels.is_lexsorted():
3393-
labels = MultiIndex.from_tuples(labels.values)
3395+
labels = labels._reconstruct(sort=True)
33943396

33953397
indexer = lexsort_indexer(labels.labels, orders=ascending,
33963398
na_position=na_position)
33973399
else:
33983400
from pandas.core.sorting import nargsort
33993401

3400-
# GH11080 - Check monotonic-ness before sort an index
3401-
# if monotonic (already sorted), return None or copy() according
3402-
# to 'inplace'
3402+
# Check monotonic-ness before sort an index
3403+
# GH11080
34033404
if ((ascending and labels.is_monotonic_increasing) or
34043405
(not ascending and labels.is_monotonic_decreasing)):
34053406
if inplace:
@@ -3410,8 +3411,9 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
34103411
indexer = nargsort(labels, kind=kind, ascending=ascending,
34113412
na_position=na_position)
34123413

3414+
baxis = self._get_block_manager_axis(axis)
34133415
new_data = self._data.take(indexer,
3414-
axis=self._get_block_manager_axis(axis),
3416+
axis=baxis,
34153417
convert=False, verify=False)
34163418

34173419
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
@@ -1756,17 +1756,31 @@ def _try_kind_sort(arr):
17561756
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
17571757
kind='quicksort', na_position='last', sort_remaining=True):
17581758

1759+
# TODO: this can be combined with DataFrame.sort_index impl as
1760+
# almost identical
17591761
inplace = validate_bool_kwarg(inplace, 'inplace')
17601762
axis = self._get_axis_number(axis)
17611763
index = self.index
1762-
if level is not None:
1764+
1765+
if level:
17631766
new_index, indexer = index.sortlevel(level, ascending=ascending,
17641767
sort_remaining=sort_remaining)
17651768
elif isinstance(index, MultiIndex):
17661769
from pandas.core.sorting import lexsort_indexer
1767-
indexer = lexsort_indexer(index.labels, orders=ascending)
1770+
labels = index._reconstruct(sort=True)
1771+
indexer = lexsort_indexer(labels.labels, orders=ascending)
17681772
else:
17691773
from pandas.core.sorting import nargsort
1774+
1775+
# Check monotonic-ness before sort an index
1776+
# GH11080
1777+
if ((ascending and index.is_monotonic_increasing) or
1778+
(not ascending and index.is_monotonic_decreasing)):
1779+
if inplace:
1780+
return
1781+
else:
1782+
return self.copy()
1783+
17701784
indexer = nargsort(index, kind=kind, ascending=ascending,
17711785
na_position=na_position)
17721786

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
@@ -1175,9 +1175,57 @@ def from_product(cls, iterables, sortorder=None, names=None):
11751175

11761176
labels, levels = _factorize_from_iterables(iterables)
11771177
labels = cartesian_product(labels)
1178+
return MultiIndex(levels, labels, sortorder=sortorder, names=names)
11781179

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

11821230
@property
11831231
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
@@ -1632,7 +1632,7 @@ def test_unstack(self):
16321632
labels=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]])
16331633
expected = DataFrame({'bar': s.values},
16341634
index=exp_index).sort_index(level=0)
1635-
unstacked = s.unstack(0)
1635+
unstacked = s.unstack(0).sort_index()
16361636
assert_frame_equal(unstacked, expected)
16371637

16381638
# GH5873

0 commit comments

Comments
 (0)