Skip to content

Commit fb6a3ee

Browse files
committed
ENH: Add support for DataFrame(Categorical) (#11363)
1 parent 37dfcc1 commit fb6a3ee

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ Other enhancements
205205
(:meth:`~DataFrame.to_parquet` / :func:`read_parquet`) using the `'pyarrow'` engine
206206
now preserve those data types with pyarrow >= 1.0.0 (:issue:`20612`).
207207
- The ``partition_cols`` argument in :meth:`DataFrame.to_parquet` now accepts a string (:issue:`27117`)
208+
- DataFrame constructor preserve `category` dtype with `Categorical` object (:issue:`11363`)
208209

209210
Build Changes
210211
^^^^^^^^^^^^^

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ def __init__(
450450

451451
# For data is list-like, or Iterable (will consume into list)
452452
elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):
453-
if not isinstance(data, abc.Sequence):
453+
if not isinstance(data, (abc.Sequence, Categorical)):
454454
data = list(data)
455455
if len(data) > 0:
456456
if is_list_like(data[0]) and getattr(data[0], "ndim", 1) == 1:

pandas/tests/frame/test_constructors.py

+6
Original file line numberDiff line numberDiff line change
@@ -2396,6 +2396,12 @@ class List(list):
23962396
result = DataFrame(List([List([1, 2, 3]), List([4, 5, 6])]))
23972397
tm.assert_frame_equal(result, expected)
23982398

2399+
def test_constructor_with_categorical(self):
2400+
# GH11363
2401+
expected = DataFrame(Series(list("aabbc"), dtype="category"))
2402+
result = DataFrame(Categorical(list("aabbc")))
2403+
tm.assert_frame_equal(result, expected)
2404+
23992405

24002406
class TestDataFrameConstructorWithDatetimeTZ:
24012407
def test_from_dict(self):

0 commit comments

Comments
 (0)