patito.DataFrame.get
- DataFrame.get(predicate=None)
Fetch the single row that matches the given polars predicate.
If you expect a data frame to already consist of one single row, you can use
.get()
without any arguments to return that row.- Raises
RowDoesNotExist – If zero rows evaluate to true for the given predicate.
MultipleRowsReturned – If more than one row evaluates to true for the given predicate.
RuntimeError – The superclass of both
RowDoesNotExist
andMultipleRowsReturned
if you want to catch both exceptions with the same class.
- Parameters
predicate (
Optional
[Expr
]) – A polars expression defining the criteria of the filter.- Returns
A pydantic-derived base model representing the given row.
- Return type
Example
>>> import patito as pt >>> import polars as pl >>> df = pt.DataFrame({"product_id": [1, 2, 3], "price": [10, 10, 20]})
The
.get()
will by default return a dynamically constructed pydantic model if no model has been associated with the given dataframe:>>> df.get(pl.col("product_id") == 1) UntypedRow(product_id=1, price=10)
If a Patito model has been associated with the dataframe, by the use of DataFrame.set_model(), then the given model will be used to represent the return type:
>>> class Product(pt.Model): ... product_id: int = pt.Field(unique=True) ... price: float ... >>> df.set_model(Product).get(pl.col("product_id") == 1) Product(product_id=1, price=10.0)
You can invoke
.get()
without any arguments on dataframes containing exactly one row:>>> df.filter(pl.col("product_id") == 1).get() UntypedRow(product_id=1, price=10)
If the given predicate matches multiple rows a
MultipleRowsReturned
will be raised:>>> try: ... df.get(pl.col("price") == 10) ... except pt.exceptions.MultipleRowsReturned as e: ... print(e) ... DataFrame.get() yielded 2 rows.
If the given predicate matches zero rows a
RowDoesNotExist
will be raised:>>> try: ... df.get(pl.col("price") == 0) ... except pt.exceptions.RowDoesNotExist as e: ... print(e) ... DataFrame.get() yielded 0 rows.