Skip to content

roundp

laktory.narwhals_ext.expr.roundp ¤

FUNCTION DESCRIPTION
roundp

Evenly round to the given precision

roundp(self, p=1.0) ¤

Evenly round to the given precision

PARAMETER DESCRIPTION
p

Precision

TYPE: float | Expr DEFAULT: 1.0

RETURNS DESCRIPTION
Expr

Output column

Examples:

import narwhals as nw
import polars as pl

import laktory as lk  # noqa: F401

df = nw.from_native(pl.DataFrame({"x": [0.781, 13.0]}))
df = df.with_columns(y=nw.col("x").laktory.roundp(p=5))
print(df)
'''
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| | x     | y    | |
| |-------|------| |
| | 0.781 | 0.0  | |
| | 13.0  | 15.0 | |
└──────────────────┘
'''

df = df.with_columns(y=nw.col("x").laktory.roundp(p=0.25))
print(df)
'''
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| | x     | y    | |
| |-------|------| |
| | 0.781 | 0.75 | |
| | 13.0  | 13.0 | |
└──────────────────┘
'''
Source code in laktory/narwhals_ext/expr/roundp.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def roundp(
    self,
    p: float | nw.Expr = 1.0,
) -> nw.Expr:
    """
    Evenly round to the given precision

    Parameters
    ------
    p:
        Precision

    Returns
    -------
    :
        Output column

    Examples
    --------
    ```py
    import narwhals as nw
    import polars as pl

    import laktory as lk  # noqa: F401

    df = nw.from_native(pl.DataFrame({"x": [0.781, 13.0]}))
    df = df.with_columns(y=nw.col("x").laktory.roundp(p=5))
    print(df)
    '''
    ┌──────────────────┐
    |Narwhals DataFrame|
    |------------------|
    | | x     | y    | |
    | |-------|------| |
    | | 0.781 | 0.0  | |
    | | 13.0  | 15.0 | |
    └──────────────────┘
    '''

    df = df.with_columns(y=nw.col("x").laktory.roundp(p=0.25))
    print(df)
    '''
    ┌──────────────────┐
    |Narwhals DataFrame|
    |------------------|
    | | x     | y    | |
    | |-------|------| |
    | | 0.781 | 0.75 | |
    | | 13.0  | 13.0 | |
    └──────────────────┘
    '''
    ```
    """
    return (self._expr / p).round() * p