Skip to content

Make DTI/TDI _union behavior match #30696

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

Merged
merged 3 commits into from
Jan 5, 2020
Merged
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
4 changes: 1 addition & 3 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,7 @@ def _union(self, other: "DatetimeIndex", sort):
result = Index._union(this, other, sort=sort)
if isinstance(result, DatetimeIndex):
assert result._data.dtype == this.dtype
if result.freq is None and (
this.freq is not None or other.freq is not None
):
if result.freq is None:
result._set_freq("infer")
return result

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexes/datetimes/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,21 @@ def test_union_freq_both_none(self, sort):
tm.assert_index_equal(result, expected)
assert result.freq is None

def test_union_freq_infer(self):
# When taking the union of two DatetimeIndexes, we infer
# a freq even if the arguments don't have freq. This matches
# TimedeltaIndex behavior.
dti = pd.date_range("2016-01-01", periods=5)
left = dti[[0, 1, 3, 4]]
right = dti[[2, 3, 1]]

assert left.freq is None
assert right.freq is None

result = left.union(right)
tm.assert_index_equal(result, dti)
assert result.freq == "D"

def test_union_dataframe_index(self):
rng1 = date_range("1/1/1999", "1/1/2012", freq="MS")
s1 = Series(np.random.randn(len(rng1)), rng1)
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexes/timedeltas/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@ def test_union_bug_4564(self):
exp = TimedeltaIndex(sorted(set(left) | set(right)))
tm.assert_index_equal(result, exp)

def test_union_freq_infer(self):
# When taking the union of two TimedeltaIndexes, we infer
# a freq even if the arguments don't have freq. This matches
# DatetimeIndex behavior.
tdi = pd.timedelta_range("1 Day", periods=5)
left = tdi[[0, 1, 3, 4]]
right = tdi[[2, 3, 1]]

assert left.freq is None
assert right.freq is None

result = left.union(right)
tm.assert_index_equal(result, tdi)
assert result.freq == "D"

def test_intersection_bug_1708(self):
index_1 = timedelta_range("1 day", periods=4, freq="h")
index_2 = index_1 + pd.offsets.Hour(5)
Expand Down