Skip to content

Commit

Permalink
python context free select
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Nov 14, 2021
1 parent e4acfba commit e68255f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 13 deletions.
1 change: 1 addition & 0 deletions py-polars/docs/source/reference/expression.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ These functions can be used as expression and sometimes also in eager contexts.
.. autosummary::
:toctree: api/

select
col
count
list
Expand Down
16 changes: 4 additions & 12 deletions py-polars/polars/lazy/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,12 @@ def _selection_to_pyexpr_list(
exprs: Union[str, "Expr", Sequence[str], Sequence["Expr"]]
) -> tp.List["PyExpr"]:
pyexpr_list: tp.List[PyExpr]
if isinstance(exprs, str):
pyexpr_list = [col(exprs)._pyexpr]
elif isinstance(exprs, (bool, int, float)):
pyexpr_list = [lit(exprs)._pyexpr]
elif isinstance(exprs, Expr):
pyexpr_list = [exprs._pyexpr]
else:
if isinstance(exprs, Sequence) and not isinstance(exprs, str):
pyexpr_list = []
for expr in exprs:
if isinstance(expr, str):
expr = col(expr)
elif isinstance(expr, (bool, int, float)):
expr = lit(expr)
pyexpr_list.append(expr._pyexpr)
pyexpr_list.append(expr_to_lit_or_expr(expr, str_to_lit=False)._pyexpr)
else:
pyexpr_list = [expr_to_lit_or_expr(exprs, str_to_lit=False)._pyexpr]
return pyexpr_list


Expand Down
43 changes: 42 additions & 1 deletion py-polars/polars/lazy/functions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import typing as tp
from datetime import date, datetime, timezone
from inspect import isclass
from typing import Any, Callable, Optional, Type, Union
from typing import Any, Callable, Optional, Sequence, Type, Union

import numpy as np

Expand Down Expand Up @@ -69,6 +69,7 @@
"format",
"_datetime",
"_date",
"select",
]


Expand Down Expand Up @@ -994,3 +995,43 @@ def collect_all(
result.append(pl.eager.frame.wrap_df(pydf))

return result


def select(
exprs: Union[str, "pl.Expr", Sequence[str], Sequence["pl.Expr"]]
) -> "pl.DataFrame":
"""
Run polars expressions without a context.
This is syntactic sugar for running `df.select` on an empty DataFrame.
Parameters
----------
exprs
Expressions to run
Returns
-------
DataFrame
Examples
--------
>>> foo = pl.Series("foo", [1, 2, 3])
>>> bar = pl.Series("bar", [3, 2, 1])
>>> pl.select([
>>> pl.min([foo, bar])
>>> ])
shape: (3, 1)
┌─────┐
│ min │
│ --- │
│ i64 │
╞═════╡
│ 1 │
├╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌┤
│ 1 │
└─────┘
"""
return pl.DataFrame([]).select(exprs)

0 comments on commit e68255f

Please sign in to comment.