Skip to content

BUG: dtype of DataFrame.idxmax/idxmin incorrect for empty frames #53296

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 8 commits into from
May 22, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
12 changes: 0 additions & 12 deletions ci/code_checks.sh
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.Period.asfreq \
pandas.Period.now \
pandas.arrays.PeriodArray \
pandas.Interval.closed \
Copy link
Member

Choose a reason for hiding this comment

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

Looks like this shouldn't be included here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, something in the rebase went wrong. I’ve updated…

pandas.Interval.left \
pandas.Interval.length \
pandas.Interval.right \
pandas.arrays.IntervalArray.left \
pandas.arrays.IntervalArray.right \
pandas.arrays.IntervalArray.closed \
pandas.arrays.IntervalArray.mid \
pandas.arrays.IntervalArray.length \
pandas.arrays.IntervalArray.is_non_overlapping_monotonic \
pandas.arrays.IntervalArray.from_arrays \
pandas.arrays.IntervalArray.to_tuples \
pandas.Int8Dtype \
Expand Down Expand Up @@ -310,9 +300,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
pandas.CategoricalIndex.as_ordered \
pandas.CategoricalIndex.as_unordered \
pandas.CategoricalIndex.equals \
pandas.IntervalIndex.closed \
pandas.IntervalIndex.values \
pandas.IntervalIndex.is_non_overlapping_monotonic \
pandas.IntervalIndex.to_tuples \
pandas.MultiIndex.dtypes \
pandas.MultiIndex.drop \
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ Reshaping
^^^^^^^^^
- Bug in :func:`crosstab` when ``dropna=False`` would not keep ``np.nan`` in the result (:issue:`10772`)
- Bug in :meth:`DataFrame.agg` and :meth:`Series.agg` on non-unique columns would return incorrect type when dist-like argument passed in (:issue:`51099`)
- Bug in :meth:`DataFrame.idxmin` and :meth:`DataFrame.idxmax`, where the axis dtype would be lost for empty frames (:issue:`53265`)
- Bug in :meth:`DataFrame.merge` not merging correctly when having ``MultiIndex`` with single level (:issue:`52331`)
- Bug in :meth:`DataFrame.stack` losing extension dtypes when columns is a :class:`MultiIndex` and frame contains mixed dtypes (:issue:`45740`)
- Bug in :meth:`DataFrame.transpose` inferring dtype for object column (:issue:`51546`)
Expand Down
32 changes: 32 additions & 0 deletions pandas/_libs/interval.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ cdef class IntervalMixin:
See Also
--------
Interval.is_empty : Indicates if an interval contains no points.

Examples
--------
>>> interval = pd.Interval(left=1, right=2, closed='left')
>>> interval
Interval(1, 2, closed='left')
>>> interval.length
1
"""
return self.right - self.left

Expand Down Expand Up @@ -369,18 +377,42 @@ cdef class Interval(IntervalMixin):
cdef readonly object left
"""
Left bound for the interval.

Examples
--------
>>> interval = pd.Interval(left=1, right=2, closed='left')
>>> interval
Interval(1, 2, closed='left')
>>> interval.left
1
"""

cdef readonly object right
"""
Right bound for the interval.

Examples
--------
>>> interval = pd.Interval(left=1, right=2, closed='left')
>>> interval
Interval(1, 2, closed='left')
>>> interval.right
2
"""

cdef readonly str closed
"""
String describing the inclusive side the intervals.

Either ``left``, ``right``, ``both`` or ``neither``.

Examples
--------
>>> interval = pd.Interval(left=1, right=2, closed='left')
>>> interval
Interval(1, 2, closed='left')
>>> interval.closed
'left'
"""

def __init__(self, left, right, str closed="right"):
Expand Down
100 changes: 100 additions & 0 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1266,6 +1266,17 @@ def _format_space(self) -> str:
def left(self):
"""
Return the left endpoints of each Interval in the IntervalArray as an Index.

Examples
--------

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(2, 5)])
>>> interv_arr
<IntervalArray>
[(0, 1], (2, 5]]
Length: 2, dtype: interval[int64, right]
>>> interv_arr.left
Index([0, 2], dtype='int64')
"""
from pandas import Index

Expand All @@ -1275,6 +1286,17 @@ def left(self):
def right(self):
"""
Return the right endpoints of each Interval in the IntervalArray as an Index.

Examples
--------

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(2, 5)])
>>> interv_arr
<IntervalArray>
[(0, 1], (2, 5]]
Length: 2, dtype: interval[int64, right]
>>> interv_arr.right
Index([1, 5], dtype='int64')
"""
from pandas import Index

Expand All @@ -1284,13 +1306,35 @@ def right(self):
def length(self) -> Index:
"""
Return an Index with entries denoting the length of each Interval.

Examples
--------

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
>>> interv_arr
<IntervalArray>
[(0, 1], (1, 5]]
Length: 2, dtype: interval[int64, right]
>>> interv_arr.length
Index([1, 4], dtype='int64')
"""
return self.right - self.left

@property
def mid(self) -> Index:
"""
Return the midpoint of each Interval in the IntervalArray as an Index.

Examples
--------

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
>>> interv_arr
<IntervalArray>
[(0, 1], (1, 5]]
Length: 2, dtype: interval[int64, right]
>>> interv_arr.mid
Index([0.5, 3.0], dtype='float64')
"""
try:
return 0.5 * (self.left + self.right)
Expand Down Expand Up @@ -1378,6 +1422,27 @@ def closed(self) -> IntervalClosedType:
String describing the inclusive side the intervals.

Either ``left``, ``right``, ``both`` or ``neither``.

Examples
--------

For arrays:

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
>>> interv_arr
<IntervalArray>
[(0, 1], (1, 5]]
Length: 2, dtype: interval[int64, right]
>>> interv_arr.closed
'right'

For Interval Index:

>>> interv_idx = pd.interval_range(start=0, end=2)
>>> interv_idx
IntervalIndex([(0, 1], (1, 2]], dtype='interval[int64, right]')
>>> interv_idx.closed
'right'
"""
return self.dtype.closed

Expand Down Expand Up @@ -1436,6 +1501,41 @@ def set_closed(self, closed: IntervalClosedType) -> Self:

Non-overlapping means (no Intervals share points), and monotonic means
either monotonic increasing or monotonic decreasing.

Examples
--------
For arrays:

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)])
>>> interv_arr
<IntervalArray>
[(0, 1], (1, 5]]
Length: 2, dtype: interval[int64, right]
>>> interv_arr.is_non_overlapping_monotonic
True

>>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1),
... pd.Interval(-1, 0.1)])
>>> interv_arr
<IntervalArray>
[(0.0, 1.0], (-1.0, 0.1]]
Length: 2, dtype: interval[float64, right]
>>> interv_arr.is_non_overlapping_monotonic
False

For Interval Index:

>>> interv_idx = pd.interval_range(start=0, end=2)
>>> interv_idx
IntervalIndex([(0, 1], (1, 2]], dtype='interval[int64, right]')
>>> interv_idx.is_non_overlapping_monotonic
True

>>> interv_idx = pd.interval_range(start=0, end=2, closed='both')
>>> interv_idx
IntervalIndex([[0, 1], [1, 2]], dtype='interval[int64, both]')
>>> interv_idx.is_non_overlapping_monotonic
False
"""

@property
Expand Down
10 changes: 10 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -11162,6 +11162,11 @@ def idxmin(
self, axis: Axis = 0, skipna: bool = True, numeric_only: bool = False
) -> Series:
axis = self._get_axis_number(axis)

if self.empty and len(self.axes[axis]):
axis_dtype = self.axes[axis].dtype
return self._constructor_sliced(dtype=axis_dtype)

if numeric_only:
data = self._get_numeric_data()
else:
Expand All @@ -11187,6 +11192,11 @@ def idxmax(
self, axis: Axis = 0, skipna: bool = True, numeric_only: bool = False
) -> Series:
axis = self._get_axis_number(axis)

if self.empty and len(self.axes[axis]):
axis_dtype = self.axes[axis].dtype
return self._constructor_sliced(dtype=axis_dtype)

if numeric_only:
data = self._get_numeric_data()
else:
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/frame/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,18 @@ def test_idxmin(self, float_frame, int_frame, skipna, axis):
expected = df.apply(Series.idxmin, axis=axis, skipna=skipna)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("axis", [0, 1])
def test_idxmin_empty(self, index, skipna, axis):
# GH53265
if axis == 0:
frame = DataFrame(index=index)
else:
frame = DataFrame(columns=index)

result = frame.idxmin(axis=axis, skipna=skipna)
expected = Series(dtype=index.dtype)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("numeric_only", [True, False])
def test_idxmin_numeric_only(self, numeric_only):
df = DataFrame({"a": [2, 3, 1], "b": [2, 1, 1], "c": list("xyx")})
Expand Down Expand Up @@ -992,6 +1004,18 @@ def test_idxmax(self, float_frame, int_frame, skipna, axis):
expected = df.apply(Series.idxmax, axis=axis, skipna=skipna)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("axis", [0, 1])
def test_idxmax_empty(self, index, skipna, axis):
# GH53265
if axis == 0:
frame = DataFrame(index=index)
else:
frame = DataFrame(columns=index)

result = frame.idxmax(axis=axis, skipna=skipna)
expected = Series(dtype=index.dtype)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("numeric_only", [True, False])
def test_idxmax_numeric_only(self, numeric_only):
df = DataFrame({"a": [2, 3, 1], "b": [2, 1, 1], "c": list("xyx")})
Expand Down