Skip to content

Handle unsortable Periods correctly in set_index, MultiIndex #18208

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

Closed
wants to merge 2 commits into from
Closed
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
11 changes: 8 additions & 3 deletions pandas/core/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,11 +431,14 @@ def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False):

def sort_mixed(values):
# order ints before strings, safe in py3
num_pos = np.array([isinstance(x, (float, int, long)) for x in values],
dtype=bool)
str_pos = np.array([isinstance(x, string_types) for x in values],
dtype=bool)
nums = np.sort(values[~str_pos])
nums = np.sort(values[num_pos])
strs = np.sort(values[str_pos])
return np.concatenate([nums, np.asarray(strs, dtype=object)])
others = values[~(str_pos | num_pos)] # We don't bother sorting these
return np.concatenate([nums, np.asarray(strs, dtype=object), others])

sorter = None
if PY3 and lib.infer_dtype(values) == 'mixed-integer':
Expand All @@ -445,7 +448,9 @@ def sort_mixed(values):
try:
sorter = values.argsort()
ordered = values.take(sorter)
except TypeError:
except (ValueError, TypeError):
# Period comparison may raise IncompatibleFrequency, which
# subclasses ValueError instead of TypeError
# try this anyway
ordered = sort_mixed(values)

Expand Down
30 changes: 30 additions & 0 deletions pandas/tests/indexes/period/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,36 @@
from ..datetimelike import DatetimeLike


class TestPeriodLevelMultiIndex(object):
# TODO: Is there a more appropriate place for these?
Copy link
Member

@gfyoung gfyoung Nov 10, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's figure that out in this PR (at first look, this location might actually be fine).

BTW, your class name isn't entirely accurate IIUC. Your first test doesn't involve a multi-index.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough. The class originally had several other tests before this PR was broken up into 3 pieces. Have a suggested name?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the 2nd should go in test_multi.py

def test_set_index(self):
# GH#17112
index = Index(['PCE'] * 4, name='Variable')
data = [Period('2018Q2'),
Period('2021', freq='5A-Dec'),
Period('2026', freq='10A-Dec'),
Period('2017Q2')]
ser = Series(data, index=index, name='Period')
df = ser.to_frame()

res = df.set_index('Period', append=True)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could go in tests/frame where we do .set_index tests

don’t add commentary

# If the doesn't raise then that's a good start
assert res.index.names == ['Variable', 'Period']

def test_from_arrays_period_level(self):
# GH#17112
index = Index(['PCE'] * 4, name='Variable')
data = [Period('2018Q2'),
Period('2021', freq='5A-Dec'),
Period('2026', freq='10A-Dec'),
Period('2017Q2')]
ser = Series(data, index=index, name='Period')

mi = pd.MultiIndex.from_arrays([ser.index, ser])
assert mi.names == ['Variable', 'Period']
assert mi.get_level_values('Variable').equals(index)


class TestPeriodIndex(DatetimeLike):
_holder = PeriodIndex
_multiprocess_can_split_ = True
Expand Down