Skip to content

ENH: Add ea support to get_dummies #50849

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 4 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all 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/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ Other enhancements
- Added ``name`` parameter to :meth:`IntervalIndex.from_breaks`, :meth:`IntervalIndex.from_arrays` and :meth:`IntervalIndex.from_tuples` (:issue:`48911`)
- Improve exception message when using :func:`assert_frame_equal` on a :class:`DataFrame` to include the column that is compared (:issue:`50323`)
- Improved error message for :func:`merge_asof` when join-columns were duplicated (:issue:`50102`)
- Added support for extension array dtypes to :func:`get_dummies` (:func:`32430`)
- Added :meth:`Index.infer_objects` analogous to :meth:`Series.infer_objects` (:issue:`50034`)
- Added ``copy`` parameter to :meth:`Series.infer_objects` and :meth:`DataFrame.infer_objects`, passing ``False`` will avoid making copies for series or columns that are already non-object or where no better dtype can be inferred (:issue:`50096`)
- :meth:`DataFrame.plot.hist` now recognizes ``xlabel`` and ``ylabel`` arguments (:issue:`49793`)
Expand Down
14 changes: 10 additions & 4 deletions pandas/core/reshape/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
is_integer_dtype,
is_list_like,
is_object_dtype,
pandas_dtype,
)

from pandas.core.arrays import SparseArray
Expand Down Expand Up @@ -240,9 +241,9 @@ def _get_dummies_1d(

if dtype is None:
dtype = np.dtype(bool)
dtype = np.dtype(dtype)
_dtype = pandas_dtype(dtype)
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 makes the annotation incorrect?


if is_object_dtype(dtype):
if is_object_dtype(_dtype):
raise ValueError("dtype=object is not a valid dtype for get_dummies")

def get_empty_frame(data) -> DataFrame:
Expand Down Expand Up @@ -317,7 +318,12 @@ def get_empty_frame(data) -> DataFrame:

else:
# take on axis=1 + transpose to ensure ndarray layout is column-major
dummy_mat = np.eye(number_of_cols, dtype=dtype).take(codes, axis=1).T
eye_dtype: NpDtype
if isinstance(_dtype, np.dtype):
eye_dtype = _dtype
else:
eye_dtype = np.bool_
dummy_mat = np.eye(number_of_cols, dtype=eye_dtype).take(codes, axis=1).T

if not dummy_na:
# reset NaN GH4446
Expand All @@ -327,7 +333,7 @@ def get_empty_frame(data) -> DataFrame:
# remove first GH12042
dummy_mat = dummy_mat[:, 1:]
dummy_cols = dummy_cols[1:]
return DataFrame(dummy_mat, index=index, columns=dummy_cols)
return DataFrame(dummy_mat, index=index, columns=dummy_cols, dtype=_dtype)


def from_dummies(
Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/reshape/test_get_dummies.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,23 @@ def test_get_dummies_with_string_values(self, values):

with pytest.raises(TypeError, match=msg):
get_dummies(df, columns=values)

def test_get_dummies_ea_dtype_series(self, any_numeric_ea_dtype):
# GH#32430
ser = Series(list("abca"))
result = get_dummies(ser, dtype=any_numeric_ea_dtype)
expected = DataFrame(
{"a": [1, 0, 0, 1], "b": [0, 1, 0, 0], "c": [0, 0, 1, 0]},
dtype=any_numeric_ea_dtype,
)
tm.assert_frame_equal(result, expected)

def test_get_dummies_ea_dtype_dataframe(self, any_numeric_ea_dtype):
# GH#32430
df = DataFrame({"x": list("abca")})
result = get_dummies(df, dtype=any_numeric_ea_dtype)
expected = DataFrame(
{"x_a": [1, 0, 0, 1], "x_b": [0, 1, 0, 0], "x_c": [0, 0, 1, 0]},
dtype=any_numeric_ea_dtype,
)
tm.assert_frame_equal(result, expected)