Skip to content

Commit ad678ca

Browse files
feat(python): 30x speedup initialising Series from python range object (#5397)
1 parent 446050b commit ad678ca

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

py-polars/polars/internals/lazy_functions.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1387,11 +1387,13 @@ def arange(
13871387
"""
13881388
low = pli.expr_to_lit_or_expr(low, str_to_lit=False)
13891389
high = pli.expr_to_lit_or_expr(high, str_to_lit=False)
1390-
13911390
if eager:
1392-
df = pli.DataFrame({"a": [1]})
1393-
return df.select(arange(low, high, step).alias("arange"))["arange"]
1394-
1391+
return (
1392+
pli.DataFrame()
1393+
.select(arange(low, high, step))
1394+
.to_series()
1395+
.rename("arange", in_place=True)
1396+
)
13951397
return pli.wrap_expr(pyarange(low._pyexpr, high._pyexpr, step))
13961398

13971399

py-polars/polars/internals/series/series.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,10 @@ def __init__(
206206
)
207207
elif isinstance(values, Series):
208208
self._s = series_to_pyseries(name, values)
209+
209210
elif _PYARROW_TYPE(values) and isinstance(values, (pa.Array, pa.ChunkedArray)):
210211
self._s = arrow_to_pyseries(name, values)
212+
211213
elif _NUMPY_TYPE(values) and isinstance(values, np.ndarray):
212214
self._s = numpy_to_pyseries(name, values, strict, nan_to_null)
213215
if values.dtype.type == np.datetime64:
@@ -223,6 +225,13 @@ def __init__(
223225

224226
if dtype is not None:
225227
self._s = self.cast(dtype, strict=True)._s
228+
229+
elif isinstance(values, range):
230+
self._s = (
231+
pli.arange(values.start, values.stop, values.step, eager=True)
232+
.rename(name, in_place=True)
233+
._s
234+
)
226235
elif isinstance(values, Sequence):
227236
self._s = sequence_to_pyseries(
228237
name, values, dtype=dtype, strict=strict, dtype_if_empty=dtype_if_empty

0 commit comments

Comments
 (0)