Skip to content

Commit

Permalink
python create Categorical Series without casting
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Nov 28, 2021
1 parent 8f198f4 commit cea0f77
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
2 changes: 2 additions & 0 deletions py-polars/polars/datatypes_constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from polars.datatypes import (
Boolean,
Categorical,
DataType,
Date,
Datetime,
Expand Down Expand Up @@ -46,6 +47,7 @@
Boolean: PySeries.new_opt_bool,
Utf8: PySeries.new_str,
Object: PySeries.new_object,
Categorical: PySeries.new_str,
}


Expand Down
7 changes: 7 additions & 0 deletions py-polars/polars/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

from polars import internals as pli
from polars.datatypes import (
Categorical,
DataType,
Date,
Datetime,
Float32,
Time,
py_type_to_arrow_type,
py_type_to_dtype,
)
Expand Down Expand Up @@ -112,6 +114,11 @@ def sequence_to_pyseries(
pyseries = pyseries.cast(str(Date), True)
elif dtype == Datetime:
pyseries = pyseries.cast(str(Datetime), True)
elif dtype == Time:
pyseries = pyseries.cast(str(Time), True)
elif dtype == Categorical:
pyseries = pyseries.cast(str(Categorical), True)

return pyseries

else:
Expand Down
6 changes: 5 additions & 1 deletion py-polars/polars/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ def assert_series_equal(
atol: float = 1.0e-8,
) -> None:
obj = "Series"
can_be_subtracted = hasattr(dtype_to_py_type(left.dtype), "__sub__")
try:
can_be_subtracted = hasattr(dtype_to_py_type(left.dtype), "__sub__")
except NotImplementedError:
can_be_subtracted = False

check_exact = check_exact or not can_be_subtracted or left.dtype == Boolean
if not (isinstance(left, Series) and isinstance(right, Series)):
raise_assert_detail(obj, "Type mismatch", type(left), type(right))
Expand Down
7 changes: 7 additions & 0 deletions py-polars/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,3 +1057,10 @@ def test_reshape() -> None:
# test lazy_dispatch
out = pl.select(pl.lit(s).reshape((-1, 1))).to_series()
assert out.series_equal(expected)


def test_init_categorical() -> None:
for values in [[None], ["foo", "bar"], [None, "foo", "bar"]]:
expected = pl.Series("a", values, dtype=pl.Utf8).cast(pl.Categorical)
a = pl.Series("a", values, dtype=pl.Categorical)
testing.assert_series_equal(a, expected)

0 comments on commit cea0f77

Please sign in to comment.