Skip to content

Commit b3caae0

Browse files
jbrockmendeljreback
authored andcommitted
Make DTI/TDI _union behavior match (#30696)
1 parent 1dcf9ca commit b3caae0

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

pandas/core/indexes/datetimes.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -394,9 +394,7 @@ def _union(self, other: "DatetimeIndex", sort):
394394
result = Index._union(this, other, sort=sort)
395395
if isinstance(result, DatetimeIndex):
396396
assert result._data.dtype == this.dtype
397-
if result.freq is None and (
398-
this.freq is not None or other.freq is not None
399-
):
397+
if result.freq is None:
400398
result._set_freq("infer")
401399
return result
402400

pandas/tests/indexes/datetimes/test_setops.py

+15
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,21 @@ def test_union_freq_both_none(self, sort):
163163
tm.assert_index_equal(result, expected)
164164
assert result.freq is None
165165

166+
def test_union_freq_infer(self):
167+
# When taking the union of two DatetimeIndexes, we infer
168+
# a freq even if the arguments don't have freq. This matches
169+
# TimedeltaIndex behavior.
170+
dti = pd.date_range("2016-01-01", periods=5)
171+
left = dti[[0, 1, 3, 4]]
172+
right = dti[[2, 3, 1]]
173+
174+
assert left.freq is None
175+
assert right.freq is None
176+
177+
result = left.union(right)
178+
tm.assert_index_equal(result, dti)
179+
assert result.freq == "D"
180+
166181
def test_union_dataframe_index(self):
167182
rng1 = date_range("1/1/1999", "1/1/2012", freq="MS")
168183
s1 = Series(np.random.randn(len(rng1)), rng1)

pandas/tests/indexes/timedeltas/test_setops.py

+15
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,21 @@ def test_union_bug_4564(self):
7878
exp = TimedeltaIndex(sorted(set(left) | set(right)))
7979
tm.assert_index_equal(result, exp)
8080

81+
def test_union_freq_infer(self):
82+
# When taking the union of two TimedeltaIndexes, we infer
83+
# a freq even if the arguments don't have freq. This matches
84+
# DatetimeIndex behavior.
85+
tdi = pd.timedelta_range("1 Day", periods=5)
86+
left = tdi[[0, 1, 3, 4]]
87+
right = tdi[[2, 3, 1]]
88+
89+
assert left.freq is None
90+
assert right.freq is None
91+
92+
result = left.union(right)
93+
tm.assert_index_equal(result, tdi)
94+
assert result.freq == "D"
95+
8196
def test_intersection_bug_1708(self):
8297
index_1 = timedelta_range("1 day", periods=4, freq="h")
8398
index_2 = index_1 + pd.offsets.Hour(5)

0 commit comments

Comments
 (0)