Skip to content

BUG/df.agg-with-df-with-missing-values-results-in-IndexError #58864

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
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Other enhancements
- Users can globally disable any ``PerformanceWarning`` by setting the option ``mode.performance_warnings`` to ``False`` (:issue:`56920`)
- :meth:`Styler.format_index_names` can now be used to format the index and column names (:issue:`48936` and :issue:`47489`)
- :class:`.errors.DtypeWarning` improved to include column names when mixed data types are detected (:issue:`58174`)
- :meth:`DataFrame.agg` now correctly handles missing values without raising an IndexError (:issue:`58810`)
Copy link
Member

Choose a reason for hiding this comment

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

This should be in the bug fix section

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Moved.

- :meth:`DataFrame.corrwith` now accepts ``min_periods`` as optional arguments, as in :meth:`DataFrame.corr` and :meth:`Series.corr` (:issue:`9490`)
- :meth:`DataFrame.cummin`, :meth:`DataFrame.cummax`, :meth:`DataFrame.cumprod` and :meth:`DataFrame.cumsum` methods now have a ``numeric_only`` parameter (:issue:`53072`)
- :meth:`DataFrame.fillna` and :meth:`Series.fillna` can now accept ``value=None``; for non-object dtype the corresponding NA value will be used (:issue:`57723`)
Expand Down
9 changes: 6 additions & 3 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1824,12 +1824,15 @@ def relabel_result(
fun = [
com.get_callable_name(f) if not isinstance(f, str) else f for f in fun
]
col_idx_order = Index(s.index).get_indexer(fun)
s = s.iloc[col_idx_order]
col_idx_order = list(Index(s.index).get_indexer(fun))
col_idx_order = [i for i in col_idx_order if 0 <= i < len(s)]
if col_idx_order:
s = s.iloc[col_idx_order]
Copy link
Member

Choose a reason for hiding this comment

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

Instead I think you can filter col_idx_order where it's equal to -1. See the get_indexer docstring

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, makes sense.


# assign the new user-provided "named aggregation" as index names, and reindex
# it based on the whole user-provided names.
s.index = reordered_indexes[idx : idx + len(fun)]
if len(s) > 0:
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if len(s) > 0:
if not s.empty:

s.index = reordered_indexes[idx : idx + len(fun)]
reordered_result_in_dict[col] = s.reindex(columns)
idx = idx + len(fun)
return reordered_result_in_dict
Expand Down
26 changes: 26 additions & 0 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,32 @@ def test_agg_ser_multi_key(df):
tm.assert_series_equal(results, expected)


def test_agg_with_missing_values():
# GH#58810
missing_df = DataFrame(
{
"nan": [np.nan, np.nan, np.nan, np.nan],
"na": [pd.NA, pd.NA, pd.NA, pd.NA],
"nat": [pd.NaT, pd.NaT, pd.NaT, pd.NaT],
"none": [None, None, None, None],
"values": [1, 2, 3, 4],
}
)

result = missing_df.agg(x=("nan", "min"), y=("na", "min"), z=("values", "sum"))

expected = DataFrame(
{
"nan": [np.nan, np.nan, np.nan],
"na": [np.nan, np.nan, np.nan],
"values": [np.nan, np.nan, 10.0],
},
index=["x", "y", "z"],
)

tm.assert_frame_equal(result, expected)


def test_groupby_aggregation_mixed_dtype():
# GH 6212
expected = DataFrame(
Expand Down