Skip to content

Commit

Permalink
Bugfix/groupby datetime issue (pandas-dev#28569)
Browse files Browse the repository at this point in the history
  • Loading branch information
sidharthann authored and proost committed Dec 19, 2019
1 parent cce4163 commit 6662b42
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ Datetimelike
- Bug in :class:`Series` and :class:`DataFrame` with integer dtype failing to raise ``TypeError`` when adding or subtracting a ``np.datetime64`` object (:issue:`28080`)
- Bug in :class:`Week` with ``weekday`` incorrectly raising ``AttributeError`` instead of ``TypeError`` when adding or subtracting an invalid type (:issue:`28530`)
- Bug in :class:`DataFrame` arithmetic operations when operating with a :class:`Series` with dtype `'timedelta64[ns]'` (:issue:`28049`)
-
- Bug in :func:`pandas.core.groupby.generic.SeriesGroupBy.apply` raising ``ValueError`` when a column in the original DataFrame is a datetime and the column labels are not standard integers (:issue:`28247`)

Timedelta
^^^^^^^^^
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1913,7 +1913,9 @@ def _recast_datetimelike_result(result: DataFrame) -> DataFrame:
result = result.copy()

obj_cols = [
idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes[idx])
idx
for idx in range(len(result.columns))
if is_object_dtype(result.dtypes.iloc[idx])
]

# See GH#26285
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,22 @@ def test_apply_with_mixed_types():

result = g.apply(lambda x: x / x.sum())
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize(
"group_column_dtlike",
[datetime.today(), datetime.today().date(), datetime.today().time()],
)
def test_apply_datetime_issue(group_column_dtlike):
# GH-28247
# groupby-apply throws an error if one of the columns in the DataFrame
# is a datetime object and the column labels are different from
# standard int values in range(len(num_columns))

df = pd.DataFrame({"a": ["foo"], "b": [group_column_dtlike]})
result = df.groupby("a").apply(lambda x: pd.Series(["spam"], index=[42]))

expected = pd.DataFrame(
["spam"], Index(["foo"], dtype="object", name="a"), columns=[42]
)
tm.assert_frame_equal(result, expected)

0 comments on commit 6662b42

Please sign in to comment.