diff --git a/crates/polars-plan/src/dsl/function_expr/pow.rs b/crates/polars-plan/src/dsl/function_expr/pow.rs index 1016e63ec487d..9ce9df789f899 100644 --- a/crates/polars-plan/src/dsl/function_expr/pow.rs +++ b/crates/polars-plan/src/dsl/function_expr/pow.rs @@ -158,7 +158,11 @@ fn pow_on_series(base: &Series, exponent: &Series) -> PolarsResult Self: """ Method equivalent of exponentiation operator `expr ** exponent`. + If the exponent is float, the result follows the dtype of exponent. + Otherwise, it follows dtype of base. + Parameters ---------- exponent @@ -5563,6 +5566,26 @@ def pow(self, exponent: IntoExprColumn | int | float) -> Self: │ 4 ┆ 64 ┆ 16.0 │ │ 8 ┆ 512 ┆ 512.0 │ └─────┴──────┴────────────┘ + + Raising an integer to a positive integer results in an integer - in order + to raise to a negative integer, you can cast either the base or the exponent + to float first: + + >>> df.with_columns( + ... x_squared = pl.col('x').pow(2), + ... x_inverse = pl.col('x').pow(-1.), + ... ) + shape: (4, 3) + ┌─────┬───────────┬───────────┐ + │ x ┆ x_squared ┆ x_inverse │ + │ --- ┆ --- ┆ --- │ + │ i64 ┆ i64 ┆ f64 │ + ╞═════╪═══════════╪═══════════╡ + │ 1 ┆ 1 ┆ 1.0 │ + │ 2 ┆ 4 ┆ 0.5 │ + │ 4 ┆ 16 ┆ 0.25 │ + │ 8 ┆ 64 ┆ 0.125 │ + └─────┴───────────┴───────────┘ """ return self.__pow__(exponent) diff --git a/py-polars/polars/series/series.py b/py-polars/polars/series/series.py index 8d9fc4bacbef7..06f966723366e 100644 --- a/py-polars/polars/series/series.py +++ b/py-polars/polars/series/series.py @@ -1877,6 +1877,9 @@ def pow(self, exponent: int | float | Series) -> Series: """ Raise to the power of the given exponent. + If the exponent is float, the result follows the dtype of exponent. + Otherwise, it follows dtype of base. + Parameters ---------- exponent @@ -1884,6 +1887,8 @@ def pow(self, exponent: int | float | Series) -> Series: Examples -------- + Raising integers to positive integers results in integers: + >>> s = pl.Series("foo", [1, 2, 3, 4]) >>> s.pow(3) shape: (4,) @@ -1894,6 +1899,19 @@ def pow(self, exponent: int | float | Series) -> Series: 27 64 ] + + In order to raise integers to negative integers, you can cast either the + base or the exponent to float: + + >>> s.pow(-3.) + shape: (4,) + Series: 'foo' [f64] + [ + 1.0 + 0.125 + 0.037037 + 0.015625 + ] """ if _check_for_numpy(exponent) and isinstance(exponent, np.ndarray): exponent = Series(exponent)