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 1 commit
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
17 changes: 14 additions & 3 deletions pandas/core/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,21 +431,32 @@ def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False):

def sort_mixed(values):
# order ints before strings, safe in py3
from pandas import Period
Copy link
Contributor

Choose a reason for hiding this comment

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

why are you going thru all this trouble? not to mention this is going to be less performant.

let's just check that things are strings or ints and be done (anything else can just return as is)

Copy link
Member Author

Choose a reason for hiding this comment

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

So don't bother sorting non-(str or int)? OK.

Copy link
Member Author

Choose a reason for hiding this comment

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

There are 4 tests that fail once we start ignoring non-(str or int); they are specifically checking for TypeErrors being raised here.

per_pos = np.array([isinstance(x, Period) 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[~(str_pos | per_pos)])
strs = np.sort(values[str_pos])
return np.concatenate([nums, np.asarray(strs, dtype=object)])
try:
pers = np.sort(values[per_pos])
except (TypeError, ValueError):
# period.IncompatibleFrequency subclasses ValueError, leads
# to inconsistent behavior in py2/py3
pers = sorted(values[per_pos], key=lambda x: x.start_time)
pers = np.array(pers, dtype=object)
return np.concatenate([nums, np.asarray(strs, dtype=object), pers])

sorter = None
if PY3 and lib.infer_dtype(values) == 'mixed-integer':
# unorderable in py3 if mixed str/int
ordered = sort_mixed(values)
else:
from pandas._libs.period import IncompatibleFrequency
try:
sorter = values.argsort()
ordered = values.take(sorter)
except TypeError:
except (TypeError, IncompatibleFrequency):
# try this anyway
ordered = sort_mixed(values)

Expand Down
45 changes: 45 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,51 @@
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)

def test_from_arrays_dataframe_level_invalid(self):
# GH#17112
index = pd.Index(['CPROF', 'HOUSING', 'INDPROD', 'NGDP', 'PGDP'],
name='Variable')
data = [pd.Period('1968Q4')] * 5
df = pd.DataFrame(data, index=index, columns=['Period'])
with pytest.raises(TypeError):
# user should not pass a DataFrame as an index level.
# In this single-column case the user needs to specifically pass
# df['Period'].
# Check that this raises at construction time instead of later
# when accessing `mi.shape`, which used to raise
# "ValueError: all arrays must be the same length",
pd.MultiIndex.from_arrays([df.index, df])


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