Skip to content

BUG: to_csv casting datetimes in categorical to int #44930

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 10 commits into from
Dec 22, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,7 @@ I/O
- Bug in :func:`read_csv` raising ``ValueError`` when names was longer than header but equal to data rows for ``engine="python"`` (:issue:`38453`)
- Bug in :class:`ExcelWriter`, where ``engine_kwargs`` were not passed through to all engines (:issue:`43442`)
- Bug in :func:`read_csv` raising ``ValueError`` when ``parse_dates`` was used with ``MultiIndex`` columns (:issue:`8991`)
- Bug in :func:`to_csv` converting datetimes in categorical :class:`Series` to integers (:issue:`40754`)
- Bug in :func:`read_csv` converting columns to numeric after date parsing failed (:issue:`11019`)
- Bug in :func:`read_csv` not replacing ``NaN`` values with ``np.nan`` before attempting date conversion (:issue:`26203`)
- Bug in :func:`read_csv` raising ``AttributeError`` when attempting to read a .csv file and infer index column dtype from an nullable integer type (:issue:`44079`)
Expand Down
8 changes: 7 additions & 1 deletion pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
)
import pandas.core.common as com
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
extract_array,
sanitize_array,
)
Expand Down Expand Up @@ -532,7 +533,12 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
else:
# GH8628 (PERF): astype category codes instead of astyping array
try:
new_cats = np.asarray(self.categories)
if is_datetime64_dtype(self.categories):
values = ensure_wrapped_if_datetimelike(np.asarray(self.categories))
Copy link
Member

Choose a reason for hiding this comment

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

self.categories._values should be what you want here. thats probably also an improvement if is_datetime64tz_dtype(self.categories.dtype)

Copy link
Member Author

Choose a reason for hiding this comment

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

tz aware datetimes are alreday handled correctly

Copy link
Member

Choose a reason for hiding this comment

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

i was thinking it might be a perf improvement for dt64tz, but either way its fine to consider that out of scope for this PR

new_cats = values._format_native_types()
else:
new_cats = np.asarray(self.categories)

new_cats = new_cats.astype(dtype=dtype, copy=copy)
fill_value = lib.item_from_zerodim(np.array(np.nan).astype(dtype))
except (
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/arrays/categorical/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
Categorical,
CategoricalIndex,
Index,
NaT,
Series,
Timestamp,
to_datetime,
)
import pandas._testing as tm

Expand Down Expand Up @@ -176,6 +178,13 @@ def test_astype_category(self, dtype_ordered, cat_ordered):
expected = cat
tm.assert_categorical_equal(result, expected)

def test_astype_object_datetime_categories(self):
# GH#40754
cat = Categorical(to_datetime(["2021-03-27", NaT], format="%Y-%m-%d"))
result = cat.astype(object)
expected = np.array(["2021-03-27", np.nan], dtype="object")
tm.assert_numpy_array_equal(result, expected)

def test_iter_python_types(self):
# GH-19909
cat = Categorical([1, 2])
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/io/formats/test_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,13 @@ def test_to_csv_date_format(self):
df_sec_grouped = df_sec.groupby([pd.Grouper(key="A", freq="1h"), "B"])
assert df_sec_grouped.mean().to_csv(date_format="%Y-%m-%d") == expected_ymd_sec

def test_to_csv_date_format_in_categorical(self):
# GH#40754
ser = pd.Series(pd.to_datetime(["2021-03-27"], format="%Y-%m-%d"))
ser = ser.astype("category")
expected = tm.convert_rows_list_to_csv_str(["0", "2021-03-27"])
assert ser.to_csv(index=False) == expected

def test_to_csv_multi_index(self):
# see gh-6618
df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]]))
Expand Down