|
| 1 | +# The remove_unused_levels defined here was copied based on the source code |
| 2 | +# defined in pandas.core.indexes.muli.py |
| 3 | + |
| 4 | +# For reference, here is a copy of the pandas copyright notice: |
| 5 | + |
| 6 | +# (c) 2011-2012, Lambda Foundry, Inc. and PyData Development Team |
| 7 | +# All rights reserved. |
| 8 | + |
| 9 | +# Copyright (c) 2008-2011 AQR Capital Management, LLC |
| 10 | +# All rights reserved. |
| 11 | + |
| 12 | +# Redistribution and use in source and binary forms, with or without |
| 13 | +# modification, are permitted provided that the following conditions are |
| 14 | +# met: |
| 15 | + |
| 16 | +# * Redistributions of source code must retain the above copyright |
| 17 | +# notice, this list of conditions and the following disclaimer. |
| 18 | + |
| 19 | +# * Redistributions in binary form must reproduce the above |
| 20 | +# copyright notice, this list of conditions and the following |
| 21 | +# disclaimer in the documentation and/or other materials provided |
| 22 | +# with the distribution. |
| 23 | + |
| 24 | +# * Neither the name of the copyright holder nor the names of any |
| 25 | +# contributors may be used to endorse or promote products derived |
| 26 | +# from this software without specific prior written permission. |
| 27 | + |
| 28 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS |
| 29 | +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 30 | +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 31 | +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 32 | +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 33 | +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 34 | +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 35 | +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 36 | +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 37 | +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 38 | +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 39 | + |
| 40 | + |
| 41 | +import numpy as np |
| 42 | +import pandas as pd |
| 43 | + |
| 44 | + |
| 45 | +# for pandas 0.19 |
| 46 | +def remove_unused_levels(self): |
| 47 | + """ |
| 48 | + create a new MultiIndex from the current that removing |
| 49 | + unused levels, meaning that they are not expressed in the labels |
| 50 | + The resulting MultiIndex will have the same outward |
| 51 | + appearance, meaning the same .values and ordering. It will also |
| 52 | + be .equals() to the original. |
| 53 | + .. versionadded:: 0.20.0 |
| 54 | + Returns |
| 55 | + ------- |
| 56 | + MultiIndex |
| 57 | + Examples |
| 58 | + -------- |
| 59 | + >>> i = pd.MultiIndex.from_product([range(2), list('ab')]) |
| 60 | + MultiIndex(levels=[[0, 1], ['a', 'b']], |
| 61 | + labels=[[0, 0, 1, 1], [0, 1, 0, 1]]) |
| 62 | + >>> i[2:] |
| 63 | + MultiIndex(levels=[[0, 1], ['a', 'b']], |
| 64 | + labels=[[1, 1], [0, 1]]) |
| 65 | + The 0 from the first level is not represented |
| 66 | + and can be removed |
| 67 | + >>> i[2:].remove_unused_levels() |
| 68 | + MultiIndex(levels=[[1], ['a', 'b']], |
| 69 | + labels=[[0, 0], [0, 1]]) |
| 70 | + """ |
| 71 | + import pandas.core.algorithms as algos |
| 72 | + |
| 73 | + new_levels = [] |
| 74 | + new_labels = [] |
| 75 | + |
| 76 | + changed = False |
| 77 | + for lev, lab in zip(self.levels, self.labels): |
| 78 | + |
| 79 | + # Since few levels are typically unused, bincount() is more |
| 80 | + # efficient than unique() - however it only accepts positive values |
| 81 | + # (and drops order): |
| 82 | + uniques = np.where(np.bincount(lab + 1) > 0)[0] - 1 |
| 83 | + has_na = int(len(uniques) and (uniques[0] == -1)) |
| 84 | + |
| 85 | + if len(uniques) != len(lev) + has_na: |
| 86 | + # We have unused levels |
| 87 | + changed = True |
| 88 | + |
| 89 | + # Recalculate uniques, now preserving order. |
| 90 | + # Can easily be cythonized by exploiting the already existing |
| 91 | + # "uniques" and stop parsing "lab" when all items are found: |
| 92 | + uniques = algos.unique(lab) |
| 93 | + if has_na: |
| 94 | + na_idx = np.where(uniques == -1)[0] |
| 95 | + # Just ensure that -1 is in first position: |
| 96 | + uniques[[0, na_idx[0]]] = uniques[[na_idx[0], 0]] |
| 97 | + |
| 98 | + # labels get mapped from uniques to 0:len(uniques) |
| 99 | + # -1 (if present) is mapped to last position |
| 100 | + label_mapping = np.zeros(len(lev) + has_na) |
| 101 | + # ... and reassigned value -1: |
| 102 | + label_mapping[uniques] = np.arange(len(uniques)) - has_na |
| 103 | + |
| 104 | + lab = label_mapping[lab] |
| 105 | + |
| 106 | + # new levels are simple |
| 107 | + lev = lev.take(uniques[has_na:]) |
| 108 | + |
| 109 | + new_levels.append(lev) |
| 110 | + new_labels.append(lab) |
| 111 | + |
| 112 | + result = self._shallow_copy() |
| 113 | + |
| 114 | + if changed: |
| 115 | + result._reset_identity() |
| 116 | + result._set_levels(new_levels, validate=False) |
| 117 | + result._set_labels(new_labels, validate=False) |
| 118 | + |
| 119 | + return result |
0 commit comments