Skip to content

Commit 4b58d3e

Browse files
committed
BUG: chokes on pd.DatetimeTZDtype if there are no rows.
This is a follow up to pandas-dev#41875
1 parent 42082a8 commit 4b58d3e

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,7 @@ Reshaping
594594
^^^^^^^^^
595595
- Bug in :meth:`DataFrame.join` inconsistently setting result index name (:issue:`55815`)
596596
- Bug in :meth:`DataFrame.unstack` producing incorrect results when ``sort=False`` (:issue:`54987`, :issue:`55516`)
597+
- Bug in :meth:`DataFrame.unstack` producing incorrect results when manipulating empty DataFrame using dtype extensions (:issue:`59123`)
597598

598599
Sparse
599600
^^^^^^

pandas/core/reshape/reshape.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,12 @@ def get_new_values(self, values, fill_value=None):
291291
# if our mask is all True, then we can use our existing dtype
292292
if mask_all:
293293
dtype = values.dtype
294-
new_values = np.empty(result_shape, dtype=dtype)
294+
if isinstance(dtype, ExtensionDtype):
295+
# GH#41875
296+
cls = dtype.construct_array_type()
297+
new_values = cls._empty(result_shape, dtype=dtype)
298+
else:
299+
new_values = np.empty(result_shape, dtype=dtype)
295300
else:
296301
if isinstance(dtype, ExtensionDtype):
297302
# GH#41875

pandas/tests/reshape/test_pivot.py

+15
Original file line numberDiff line numberDiff line change
@@ -2769,3 +2769,18 @@ def test_unstack_copy(self, m):
27692769
result = df.unstack(sort=False)
27702770
result.iloc[0, 0] = -1
27712771
tm.assert_frame_equal(df, df_orig)
2772+
2773+
@pytest.mark.parametrize("tz", [None, "UTC"])
2774+
def test_pivot_empty_with_datetime(self, tz):
2775+
# GH#59126
2776+
df = DataFrame(
2777+
{
2778+
"timestamp": [pd.Timestamp("2024-01-01T00:00", tz=tz)],
2779+
"category": ["A"],
2780+
"value": [100],
2781+
}
2782+
)
2783+
df_pivoted = df[df.category == "C"].pivot_table(
2784+
index="category", columns="value", values="timestamp"
2785+
)
2786+
assert df_pivoted.empty

0 commit comments

Comments
 (0)