diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4fcd24504..796d5588b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,11 +15,13 @@ jobs: strategy: matrix: include: - - otp_version: 25.3 - elixir_version: 1.15 + - otp_version: "27.3" + elixir_version: "1.18" + runner: ubuntu-latest - - otp_version: "27.2" - elixir_version: 1.18 + - otp_version: "29.1" + elixir_version: "1.20" + runner: ubuntu-latest runs-on: ubuntu-latest name: test diff --git a/CHANGELOG.md b/CHANGELOG.md index 00b618295..6047b44c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Added `Explorer.Series.starts_with/2` and `Explorer.Series.ends_with/2`, which + detect literal prefixes and suffixes without needing a regular expression. +- Added `Explorer.Series.is_unique/1` and `Explorer.Series.is_duplicated/1`, which + return a boolean mask marking the values that appear exactly once or more than once. +- Added `Explorer.Series.diff/2`, which calculates the difference between + consecutive values, with `:n` and `:null_behavior` options. +- Added `Explorer.Series.kurtosis/2`, which computes the sample kurtosis of a + series, with `:fisher` and `:bias` options. +- Added `Explorer.Series.sign/1`, which returns the sign of each value in a series. + ## [v0.13.0] - 2026-09-28 ### Added diff --git a/lib/explorer/backend/lazy_series.ex b/lib/explorer/backend/lazy_series.ex index b5afc1d66..6729b8f01 100644 --- a/lib/explorer/backend/lazy_series.ex +++ b/lib/explorer/backend/lazy_series.ex @@ -55,6 +55,10 @@ defmodule Explorer.Backend.LazySeries do cast: 2, select: 3, abs: 1, + sign: 1, + is_unique: 1, + is_duplicated: 1, + diff: 3, strptime: 2, strftime: 2, clip_float: 3, @@ -122,6 +126,7 @@ defmodule Explorer.Backend.LazySeries do nil_count: 1, size: 1, skew: 2, + kurtosis: 3, correlation: 3, covariance: 3, all: 1, @@ -130,6 +135,8 @@ defmodule Explorer.Backend.LazySeries do rle_id: 1, # Strings contains: 2, + starts_with: 2, + ends_with: 2, re_contains: 2, replace: 3, re_replace: 3, @@ -588,6 +595,14 @@ defmodule Explorer.Backend.LazySeries do Backend.Series.new(data, {:f, 64}) end + @impl true + def kurtosis(%Series{} = series, fisher, bias) do + args = [series_or_lazy_series!(series), fisher, bias] + data = new(:kurtosis, args, {:f, 64}, true) + + Backend.Series.new(data, {:f, 64}) + end + @impl true def correlation(%Series{} = left, %Series{} = right, method) do args = [series_or_lazy_series!(left), series_or_lazy_series!(right), method] @@ -931,6 +946,13 @@ defmodule Explorer.Backend.LazySeries do Backend.Series.new(data, series.dtype) end + @impl true + def sign(%Series{} = series) do + data = new(:sign, [lazy_series!(series)], series.dtype) + + Backend.Series.new(data, series.dtype) + end + @impl true def strptime(%Series{} = series, format_string) do dtype = {:naive_datetime, :microsecond} @@ -1102,6 +1124,20 @@ defmodule Explorer.Backend.LazySeries do Backend.Series.new(data, :boolean) end + @impl true + def starts_with(series, prefix) do + data = new(:starts_with, [lazy_series!(series), prefix], :boolean) + + Backend.Series.new(data, :boolean) + end + + @impl true + def ends_with(series, suffix) do + data = new(:ends_with, [lazy_series!(series), suffix], :boolean) + + Backend.Series.new(data, :boolean) + end + @impl true def re_contains(series, pattern) do data = new(:re_contains, [lazy_series!(series), pattern], :boolean) @@ -1263,6 +1299,52 @@ defmodule Explorer.Backend.LazySeries do Backend.Series.new(data, {:u, 32}) end + @impl true + def is_unique(series) do + args = [lazy_series!(series)] + + if aggregations?(args), do: raise_agg_inside_window(:is_unique) + + data = new(:is_unique, args, :boolean, false) + + Backend.Series.new(data, :boolean) + end + + @impl true + def is_duplicated(series) do + args = [lazy_series!(series)] + + if aggregations?(args), do: raise_agg_inside_window(:is_duplicated) + + data = new(:is_duplicated, args, :boolean, false) + + Backend.Series.new(data, :boolean) + end + + @impl true + def diff(series, n, null_behavior) do + args = [lazy_series!(series), n, null_behavior] + + if aggregations?(args), do: raise_agg_inside_window(:diff) + + dtype = diff_dtype(series.dtype) + data = new(:diff, args, dtype, false) + + Backend.Series.new(data, dtype) + end + + # Mirrors the output dtype that Polars computes for `diff`. + defp diff_dtype({:datetime, precision, _time_zone}), do: {:duration, precision} + defp diff_dtype({:naive_datetime, precision}), do: {:duration, precision} + defp diff_dtype(:date), do: {:duration, :microsecond} + defp diff_dtype(:time), do: {:duration, :nanosecond} + defp diff_dtype({:u, 64}), do: {:s, 64} + defp diff_dtype({:u, 32}), do: {:s, 64} + defp diff_dtype({:u, 16}), do: {:s, 32} + defp diff_dtype({:u, 8}), do: {:s, 16} + defp diff_dtype({:decimal, _precision, scale}), do: {:decimal, 38, scale} + defp diff_dtype(dtype), do: dtype + @impl true def count_matches(series, substring) do data = new(:count_matches, [lazy_series!(series), substring], {:u, 32}) diff --git a/lib/explorer/backend/series.ex b/lib/explorer/backend/series.ex index 92191d667..b699055b2 100644 --- a/lib/explorer/backend/series.ex +++ b/lib/explorer/backend/series.ex @@ -89,12 +89,17 @@ defmodule Explorer.Backend.Series do @callback nil_count(s) :: number() | lazy_s() @callback product(s) :: float() | non_finite() | lazy_s() | nil @callback skew(s, bias? :: boolean()) :: float() | non_finite() | lazy_s() | nil + @callback kurtosis(s, fisher? :: boolean(), bias? :: boolean()) :: + float() | non_finite() | lazy_s() | nil @callback correlation(s, s, method :: atom()) :: float() | non_finite() | lazy_s() | nil @callback covariance(s, s, ddof :: non_neg_integer()) :: float() | non_finite() | lazy_s() | nil @callback all?(s) :: boolean() | lazy_s() @callback any?(s) :: boolean() | lazy_s() @callback row_index(s) :: s | lazy_s() @callback rle_id(s) :: s | lazy_s() + @callback is_unique(s) :: s | lazy_s() + @callback is_duplicated(s) :: s | lazy_s() + @callback diff(s, n :: integer(), null_behavior :: :ignore | :drop) :: s | lazy_s() # Cumulative @@ -121,6 +126,7 @@ defmodule Explorer.Backend.Series do @callback log(argument :: s, base :: float()) :: s @callback exp(s) :: s @callback abs(s) :: s + @callback sign(s) :: s @callback clip(s, number(), number()) :: s # Trigonometry @@ -300,6 +306,8 @@ defmodule Explorer.Backend.Series do # Strings @callback contains(s, String.t()) :: s + @callback starts_with(s, String.t()) :: s + @callback ends_with(s, String.t()) :: s @callback upcase(s) :: s @callback downcase(s) :: s @callback replace(s, String.t(), String.t()) :: s @@ -357,6 +365,7 @@ defmodule Explorer.Backend.Series do %Explorer.Series{data: data, dtype: dtype} end + @default_limit 50 alias Inspect.Algebra, as: A alias Explorer.Series @@ -366,6 +375,7 @@ defmodule Explorer.Backend.Series do def inspect(series, backend, n_rows, inspect_opts, opts \\ []) when is_binary(backend) and (is_integer(n_rows) or is_nil(n_rows) or is_binary(n_rows)) and is_list(opts) do + inspect_opts = %{inspect_opts | limit: @default_limit} open = A.color("[", :list, inspect_opts) close = A.color("]", :list, inspect_opts) diff --git a/lib/explorer/polars_backend/expression.ex b/lib/explorer/polars_backend/expression.ex index 6363b91a1..a754770a1 100644 --- a/lib/explorer/polars_backend/expression.ex +++ b/lib/explorer/polars_backend/expression.ex @@ -43,6 +43,9 @@ defmodule Explorer.PolarsBackend.Expression do equal: 2, exp: 1, abs: 1, + sign: 1, + is_unique: 1, + is_duplicated: 1, fill_missing_with_value: 2, first: 1, format: 1, @@ -102,6 +105,8 @@ defmodule Explorer.PolarsBackend.Expression do sample_frac: 5, exp: 1, skew: 2, + kurtosis: 3, + diff: 3, round: 2, clip_float: 3, clip_integer: 3, @@ -140,6 +145,8 @@ defmodule Explorer.PolarsBackend.Expression do # Strings contains: 2, + starts_with: 2, + ends_with: 2, re_contains: 2, replace: 3, re_replace: 3, diff --git a/lib/explorer/polars_backend/lazy_frame.ex b/lib/explorer/polars_backend/lazy_frame.ex index 07ed4b455..8538d31aa 100644 --- a/lib/explorer/polars_backend/lazy_frame.ex +++ b/lib/explorer/polars_backend/lazy_frame.ex @@ -94,9 +94,15 @@ defmodule Explorer.PolarsBackend.LazyFrame do # IO @impl true - def from_query(conn, query, params) do - with {:ok, df} <- Eager.from_query(conn, query, params) do - {:ok, Eager.lazy(df)} + if Code.ensure_loaded?(Adbc) do + def from_query(conn, query, params) do + with {:ok, df} <- Eager.from_query(conn, query, params) do + {:ok, Eager.lazy(df)} + end + end + else + def from_query(_conn, _query, _params) do + raise "you must install :adbc as a dependency in order to use from_query/3" end end diff --git a/lib/explorer/polars_backend/native.ex b/lib/explorer/polars_backend/native.ex index 0e16f9d8c..62936bc07 100644 --- a/lib/explorer/polars_backend/native.ex +++ b/lib/explorer/polars_backend/native.ex @@ -335,6 +335,7 @@ defmodule Explorer.PolarsBackend.Native do def s_cumulative_count(_s, _reverse), do: err() def s_cumulative_product(_s, _reverse), do: err() def s_skew(_s, _bias), do: err() + def s_kurtosis(_s, _fisher, _bias), do: err() def s_correlation(_s1, _s2, _method), do: err() def s_covariance(_s1, _s2, _ddof), do: err() def s_distinct(_s), do: err() @@ -428,6 +429,12 @@ defmodule Explorer.PolarsBackend.Native do def s_round(_s, _decimals), do: err() def s_row_index(_s), do: err() def s_rle_id(_s), do: err() + def s_is_unique(_s), do: err() + def s_is_duplicated(_s), do: err() + def s_diff(_s, _n, _null_behavior), do: err() + def s_sign(_s), do: err() + def s_starts_with(_s, _prefix), do: err() + def s_ends_with(_s, _suffix), do: err() def s_floor(_s), do: err() def s_ceil(_s), do: err() def s_rstrip(_s, _string), do: err() diff --git a/lib/explorer/polars_backend/series.ex b/lib/explorer/polars_backend/series.ex index 4f60a4064..1f913615f 100644 --- a/lib/explorer/polars_backend/series.ex +++ b/lib/explorer/polars_backend/series.ex @@ -236,6 +236,10 @@ defmodule Explorer.PolarsBackend.Series do def skew(series, bias?), do: Shared.apply_series(series, :s_skew, [bias?]) + @impl true + def kurtosis(series, fisher?, bias?), + do: Shared.apply_series(series, :s_kurtosis, [fisher?, bias?]) + @impl true def correlation(left, right, method), do: Shared.apply_series(matching_size!(left, right), :s_correlation, [right.data, method]) @@ -256,6 +260,16 @@ defmodule Explorer.PolarsBackend.Series do @impl true def rle_id(series), do: Shared.apply_series(series, :s_rle_id) + @impl true + def is_unique(series), do: Shared.apply_series(series, :s_is_unique) + + @impl true + def is_duplicated(series), do: Shared.apply_series(series, :s_is_duplicated) + + @impl true + def diff(series, n, null_behavior), + do: Shared.apply_series(series, :s_diff, [n, null_behavior]) + # Cumulative @impl true @@ -391,6 +405,9 @@ defmodule Explorer.PolarsBackend.Series do @impl true def abs(%Series{} = s), do: Shared.apply_series(s, :s_abs, []) + @impl true + def sign(%Series{} = s), do: Shared.apply_series(s, :s_sign, []) + @impl true def clip(%Series{dtype: dtype} = s, min, max) when dtype in @integer_types and is_integer(min) and is_integer(max), @@ -699,6 +716,14 @@ defmodule Explorer.PolarsBackend.Series do def contains(series, substring), do: Shared.apply_series(series, :s_contains, [substring, true]) + @impl true + def starts_with(series, prefix), + do: Shared.apply_series(series, :s_starts_with, [prefix]) + + @impl true + def ends_with(series, suffix), + do: Shared.apply_series(series, :s_ends_with, [suffix]) + @impl true def re_contains(series, pattern), do: Shared.apply_series(series, :s_contains, [pattern, false]) diff --git a/lib/explorer/series.ex b/lib/explorer/series.ex index b3777b752..894389562 100644 --- a/lib/explorer/series.ex +++ b/lib/explorer/series.ex @@ -2915,6 +2915,62 @@ defmodule Explorer.Series do def skew(%Series{dtype: dtype}, _), do: dtype_error("skew/2", dtype, @numeric_dtypes) + @doc """ + Compute the sample kurtosis of a series. + + Kurtosis measures how much of the distribution's variance comes from + infrequent, extreme deviations rather than frequent, modest ones. + + ## Options + + * `:fisher` - If `true` (the default), Fisher's definition is used, which + subtracts 3 so that a normal distribution has a kurtosis of `0.0`. If + `false`, Pearson's definition is used and a normal distribution has a + kurtosis of `3.0`. + + * `:bias` - If `false`, the calculation is corrected for statistical bias. + Defaults to `true`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5, 23]) + iex> Explorer.Series.kurtosis(s) + 0.9945668771797536 + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5, 23]) + iex> Explorer.Series.kurtosis(s, fisher: false) + 3.9945668771797536 + + iex> s = Explorer.Series.from_list([1, 2, 3, 4, 5, 23]) + iex> Explorer.Series.kurtosis(s, bias: false) + 5.400820058440949 + + iex> s = Explorer.Series.from_list([1, 2, 3, nil, 1]) + iex> Explorer.Series.kurtosis(s) + -1.371900826446281 + + iex> s = Explorer.Series.from_list([true, false, true]) + iex> Explorer.Series.kurtosis(s) + ** (ArgumentError) Explorer.Series.kurtosis/2 not implemented for dtype :boolean. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :aggregation + @spec kurtosis(series :: Series.t(), opts :: Keyword.t()) :: + float() | non_finite() | lazy_t() | nil + def kurtosis(series, opts \\ []) + + def kurtosis(%Series{dtype: dtype} = series, opts) when is_numeric_dtype(dtype) do + opts = Keyword.validate!(opts, fisher: true, bias: true) + apply_series(series, :kurtosis, [opts[:fisher], opts[:bias]]) + end + + def kurtosis(%Series{dtype: dtype}, _), + do: dtype_error("kurtosis/2", dtype, @numeric_dtypes) + @doc """ Compute the correlation between two series. @@ -3156,6 +3212,168 @@ defmodule Explorer.Series do def rle_id(%Series{} = series), do: apply_series(series, :rle_id) + @doc """ + Returns a boolean mask marking the values that appear exactly once. + + See `is_duplicated/1` for the inverse, and `distinct/1` if you want the + distinct values themselves rather than a mask. + + ## Supported dtypes + + All except `:list` and `:struct`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 2, 3]) + iex> Explorer.Series.is_unique(s) + #Explorer.Series< + Polars[4] + boolean [true, false, false, true] + > + + `nil` is treated as a value, so repeated `nil`s are not unique: + + iex> s = Explorer.Series.from_list(["a", nil, "b", nil]) + iex> Explorer.Series.is_unique(s) + #Explorer.Series< + Polars[4] + boolean [true, false, true, false] + > + """ + @doc type: :element_wise + @spec is_unique(series :: Series.t()) :: Series.t() + def is_unique(%Series{dtype: {composite, _} = dtype}) when K.in(composite, [:list, :struct]), + do: dtype_error("is_unique/1", dtype, Shared.dtypes() -- [{:list, :any}, {:struct, :any}]) + + def is_unique(%Series{} = series), + do: apply_series(series, :is_unique) + + @doc """ + Returns a boolean mask marking the values that appear more than once. + + This is the inverse of `is_unique/1`, and is useful for inspecting the + duplicated rows that `distinct/1` would collapse. + + ## Supported dtypes + + All except `:list` and `:struct`. + + ## Examples + + iex> s = Explorer.Series.from_list([1, 2, 2, 3]) + iex> Explorer.Series.is_duplicated(s) + #Explorer.Series< + Polars[4] + boolean [false, true, true, false] + > + + Combined with `Explorer.DataFrame.filter_with/2`, this keeps only the rows + whose key occurs more than once: + + iex> require Explorer.DataFrame, as: DF + iex> df = DF.new(id: ["a", "b", "a", "c"]) + iex> DF.filter(df, is_duplicated(id)) + #Explorer.DataFrame< + Polars[2 x 1] + id string ["a", "a"] + > + """ + @doc type: :element_wise + @spec is_duplicated(series :: Series.t()) :: Series.t() + def is_duplicated(%Series{dtype: {composite, _} = dtype}) + when K.in(composite, [:list, :struct]), + do: + dtype_error( + "is_duplicated/1", + dtype, + Shared.dtypes() -- [{:list, :any}, {:struct, :any}] + ) + + def is_duplicated(%Series{} = series), + do: apply_series(series, :is_duplicated) + + @doc """ + Calculates the difference between consecutive values. + + Because this function depends on the order of the rows, it may be necessary + to sort your data frame prior to running this function to get the results + that you desire. When used inside `Explorer.DataFrame.mutate/2` on a grouped + data frame, the difference is calculated within each group. + + Subtracting temporal values yields a duration: `:date` becomes + `{:duration, :microsecond}`, `:time` becomes `{:duration, :nanosecond}`, and + datetimes become a duration of the same precision. Unsigned integers are + widened to a signed integer so that negative differences are representable. + + ## Options + + * `:n` - The number of rows to look back. Defaults to `1`. A negative + value looks forward instead. + + * `:null_behavior` - What to do with the `n` values that have no + predecessor. `:ignore` (the default) leaves them as `nil`, keeping the + series the same length. `:drop` removes them, which makes the series + shorter and therefore cannot be used inside `Explorer.DataFrame.mutate/2`. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + * `:date` + * `:time` + * `:datetime` + * `:duration` + + ## Examples + + iex> s = Explorer.Series.from_list([1, 3, 6, 10]) + iex> Explorer.Series.diff(s) + #Explorer.Series< + Polars[4] + s64 [nil, 2, 3, 4] + > + + Look back further with `:n`: + + iex> s = Explorer.Series.from_list([1, 3, 6, 10]) + iex> Explorer.Series.diff(s, n: 2) + #Explorer.Series< + Polars[4] + s64 [nil, nil, 5, 7] + > + + Drop the leading `nil`s instead of keeping them: + + iex> s = Explorer.Series.from_list([1, 3, 6, 10]) + iex> Explorer.Series.diff(s, null_behavior: :drop) + #Explorer.Series< + Polars[3] + s64 [2, 3, 4] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.diff(s) + ** (ArgumentError) Explorer.Series.diff/2 not implemented for dtype :string. Valid dtypes are :date, :time, {:duration, :microsecond}, {:duration, :millisecond}, {:duration, :nanosecond}, {:f, 32}, {:f, 64}, {:naive_datetime, :microsecond}, {:naive_datetime, :millisecond}, {:naive_datetime, :nanosecond}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :window + @spec diff(series :: Series.t(), opts :: Keyword.t()) :: Series.t() + def diff(series, opts \\ []) + + def diff(%Series{dtype: dtype} = series, opts) when is_numeric_or_temporal_dtype(dtype) do + opts = Keyword.validate!(opts, n: 1, null_behavior: :ignore) + + if K.in(opts[:null_behavior], [:ignore, :drop]) do + apply_series(series, :diff, [opts[:n], opts[:null_behavior]]) + else + raise ArgumentError, + "expected :null_behavior to be :ignore or :drop, " <> + "got: #{inspect(opts[:null_behavior])}" + end + end + + def diff(%Series{dtype: dtype}, _), + do: dtype_error("diff/2", dtype, @numeric_or_temporal_dtypes) + # Cumulative @doc """ @@ -5743,6 +5961,46 @@ defmodule Explorer.Series do def abs(%Series{dtype: dtype}), do: dtype_error("abs/1", dtype, @numeric_dtypes) + @doc """ + Returns the sign of each value in the series. + + The sign is `-1` for negative values, `0` for zero and `1` for positive + values. `nil` values are preserved, and the result keeps the dtype of the + input series. + + ## Supported dtypes + + * floats: #{Shared.inspect_dtypes(@float_dtypes, backticks: true)} + * integers: #{Shared.inspect_dtypes(@integer_types, backticks: true)} + + ## Examples + + iex> s = Explorer.Series.from_list([-3, 0, 4]) + iex> Explorer.Series.sign(s) + #Explorer.Series< + Polars[3] + s64 [-1, 0, 1] + > + + iex> s = Explorer.Series.from_list([-3.0, 0.0, 4.5, nil]) + iex> Explorer.Series.sign(s) + #Explorer.Series< + Polars[4] + f64 [-1.0, 0.0, 1.0, nil] + > + + iex> s = Explorer.Series.from_list(["a", "b", "c"]) + iex> Explorer.Series.sign(s) + ** (ArgumentError) Explorer.Series.sign/1 not implemented for dtype :string. Valid dtypes are {:f, 32}, {:f, 64}, {:s, 8}, {:s, 16}, {:s, 32}, {:s, 64}, {:u, 8}, {:u, 16}, {:u, 32} and {:u, 64} + """ + @doc type: :element_wise + @spec sign(series :: Series.t()) :: Series.t() + def sign(%Series{dtype: dtype} = series) when is_numeric_dtype(dtype), + do: apply_series(series, :sign) + + def sign(%Series{dtype: dtype}), + do: dtype_error("sign/1", dtype, @numeric_dtypes) + # Strings @doc """ @@ -5769,6 +6027,68 @@ defmodule Explorer.Series do def contains(%Series{dtype: dtype}, _), do: dtype_error("contains/2", dtype, [:string]) + @doc """ + Detects whether a string starts with a prefix. + + > ### Notice {: .warning} + > + > This function detects only literal strings. For regular expressions, see `re_contains/2`. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def", "bcd"]) + iex> Explorer.Series.starts_with(s, "a") + #Explorer.Series< + Polars[3] + boolean [true, false, false] + > + + iex> s = Explorer.Series.from_list(["abc", nil, "bcd"]) + iex> Explorer.Series.starts_with(s, "bc") + #Explorer.Series< + Polars[3] + boolean [false, nil, true] + > + """ + @doc type: :string_wise + @spec starts_with(Series.t(), String.t()) :: Series.t() + def starts_with(%Series{dtype: :string} = series, prefix) + when K.is_binary(prefix), + do: apply_series(series, :starts_with, [prefix]) + + def starts_with(%Series{dtype: dtype}, _), do: dtype_error("starts_with/2", dtype, [:string]) + + @doc """ + Detects whether a string ends with a suffix. + + > ### Notice {: .warning} + > + > This function detects only literal strings. For regular expressions, see `re_contains/2`. + + ## Examples + + iex> s = Explorer.Series.from_list(["abc", "def", "bcd"]) + iex> Explorer.Series.ends_with(s, "d") + #Explorer.Series< + Polars[3] + boolean [false, false, true] + > + + iex> s = Explorer.Series.from_list(["abc", nil, "bcd"]) + iex> Explorer.Series.ends_with(s, "bc") + #Explorer.Series< + Polars[3] + boolean [true, nil, false] + > + """ + @doc type: :string_wise + @spec ends_with(Series.t(), String.t()) :: Series.t() + def ends_with(%Series{dtype: :string} = series, suffix) + when K.is_binary(suffix), + do: apply_series(series, :ends_with, [suffix]) + + def ends_with(%Series{dtype: dtype}, _), do: dtype_error("ends_with/2", dtype, [:string]) + @doc """ Detects whether a string matches a pattern. diff --git a/native/explorer/Cargo.toml b/native/explorer/Cargo.toml index 871e87eb0..acc509cc0 100644 --- a/native/explorer/Cargo.toml +++ b/native/explorer/Cargo.toml @@ -50,6 +50,7 @@ features = [ "cutqcut", "decompress", "describe", + "diff", "dtype-full", "ewma", "extract_groups", @@ -57,6 +58,7 @@ features = [ "ipc_streaming", "ipc", "is_in", + "is_unique", "lazy", "log", "mode", @@ -76,6 +78,7 @@ features = [ "rolling_window", "round_series", "rows", + "sign", "simd", "sql", "strings", @@ -90,7 +93,17 @@ features = [ [dependencies.polars-ops] version = "0.55" -features = ["abs", "ewma", "cum_agg", "cov", "index_of", "rle"] +features = [ + "abs", + "ewma", + "cum_agg", + "cov", + "diff", + "index_of", + "is_unique", + "moment", + "rle", +] [features] default = ["ndjson", "cloud", "nif_version_2_15"] diff --git a/native/explorer/src/datatypes.rs b/native/explorer/src/datatypes.rs index 7b0a70bea..d46bbc4ef 100644 --- a/native/explorer/src/datatypes.rs +++ b/native/explorer/src/datatypes.rs @@ -10,6 +10,7 @@ use polars::polars_utils::compression::{BrotliLevel, GzipLevel, ZstdLevel}; #[cfg(feature = "cloud")] use polars::prelude::cloud::CloudOptions; use polars::prelude::*; +use polars::series::ops::NullBehavior; use rustler::{Atom, NifStruct, NifTaggedEnum, Resource, ResourceArc}; use std::fmt; use std::ops::Deref; @@ -766,6 +767,21 @@ pub enum ExCorrelationMethod { Spearman, } +#[derive(NifTaggedEnum)] +pub enum ExNullBehavior { + Ignore, + Drop, +} + +impl From for NullBehavior { + fn from(value: ExNullBehavior) -> Self { + match value { + ExNullBehavior::Ignore => NullBehavior::Ignore, + ExNullBehavior::Drop => NullBehavior::Drop, + } + } +} + #[derive(NifTaggedEnum)] pub enum ExRankMethod { Average, diff --git a/native/explorer/src/expressions.rs b/native/explorer/src/expressions.rs index 2184e4533..18fd998af 100644 --- a/native/explorer/src/expressions.rs +++ b/native/explorer/src/expressions.rs @@ -5,8 +5,8 @@ // wrapped in an Elixir struct. use crate::datatypes::{ - ExCorrelationMethod, ExDate, ExDateTime, ExDuration, ExNaiveDateTime, ExRankMethod, - ExSeriesDtype, ExValidValue, + ExCorrelationMethod, ExDate, ExDateTime, ExDuration, ExNaiveDateTime, ExNullBehavior, + ExRankMethod, ExSeriesDtype, ExValidValue, }; use crate::series::{cast_str_to_f64, ewm_opts, rolling_opts_fixed_window, shuffle_option}; use crate::{ExDataFrame, ExExpr, ExSeries}; @@ -525,6 +525,12 @@ pub fn expr_skew(data: ExExpr, bias: bool) -> ExExpr { ExExpr::new(expr.skew(bias)) } +#[rustler::nif] +pub fn expr_kurtosis(data: ExExpr, fisher: bool, bias: bool) -> ExExpr { + let expr = data.clone_inner(); + ExExpr::new(expr.kurtosis(fisher, bias)) +} + #[rustler::nif] pub fn expr_correlation(left: ExExpr, right: ExExpr, method: ExCorrelationMethod) -> ExExpr { let left_expr = left.clone_inner().cast(DataType::Float64); @@ -786,6 +792,34 @@ pub fn expr_rle_id(expr: ExExpr) -> ExExpr { ExExpr::new(expr.rle_id()) } +#[rustler::nif] +pub fn expr_sign(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.sign()) +} + +#[rustler::nif] +pub fn expr_is_unique(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_unique()) +} + +#[rustler::nif] +pub fn expr_is_duplicated(expr: ExExpr) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.is_duplicated()) +} + +#[rustler::nif] +pub fn expr_diff(expr: ExExpr, n: i64, null_behavior: ExNullBehavior) -> ExExpr { + let expr = expr.clone_inner(); + + ExExpr::new(expr.diff(lit(n), null_behavior.into())) +} + #[rustler::nif] pub fn expr_sort( expr: ExExpr, @@ -856,6 +890,18 @@ pub fn expr_contains(expr: ExExpr, pattern: &str) -> ExExpr { ExExpr::new(expr.str().contains_literal(pattern.lit())) } +#[rustler::nif] +pub fn expr_starts_with(expr: ExExpr, prefix: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().starts_with(prefix.lit())) +} + +#[rustler::nif] +pub fn expr_ends_with(expr: ExExpr, suffix: &str) -> ExExpr { + let expr = expr.clone_inner(); + ExExpr::new(expr.str().ends_with(suffix.lit())) +} + #[rustler::nif] pub fn expr_re_contains(expr: ExExpr, pattern: &str) -> ExExpr { let expr = expr.clone_inner(); diff --git a/native/explorer/src/series.rs b/native/explorer/src/series.rs index 39ac96605..87b04c2a3 100644 --- a/native/explorer/src/series.rs +++ b/native/explorer/src/series.rs @@ -1,7 +1,7 @@ use crate::{ datatypes::{ ex_naive_datetime_to_timestamp, ExCorrelationMethod, ExDate, ExDecimal, ExNaiveDateTime, - ExRankMethod, ExSeriesDtype, ExTime, ExTimeUnit, ExValidValue, + ExNullBehavior, ExRankMethod, ExSeriesDtype, ExTime, ExTimeUnit, ExValidValue, }, encoding, ExDataFrame, ExSeries, ExplorerError, }; @@ -1010,6 +1010,15 @@ pub fn s_skew(env: Env, s: ExSeries, bias: bool) -> Result } } +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_kurtosis(env: Env, s: ExSeries, fisher: bool, bias: bool) -> Result { + if is_numeric(s.dtype()) { + Ok(term_from_optional_float(s.kurtosis(fisher, bias)?, env)) + } else { + panic!("kurtosis/2 not implemented for {:?}", &s.dtype()) + } +} + #[rustler::nif(schedule = "DirtyCpu")] pub fn s_correlation( env: Env, @@ -1431,6 +1440,36 @@ pub fn s_contains(s1: ExSeries, pattern: &str, literal: bool) -> Result Result { + let series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).str().starts_with(prefix.lit())]) + .collect()? + .column(s.name())? + .as_materialized_series() + .clone(); + + Ok(ExSeries::new(series)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_ends_with(s: ExSeries, suffix: &str) -> Result { + let series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).str().ends_with(suffix.lit())]) + .collect()? + .column(s.name())? + .as_materialized_series() + .clone(); + + Ok(ExSeries::new(series)) +} + #[rustler::nif(schedule = "DirtyCpu")] pub fn s_upcase(s1: ExSeries) -> Result { Ok(ExSeries::new(s1.str()?.to_uppercase().into())) @@ -1997,6 +2036,47 @@ pub fn s_rle_id(series: ExSeries) -> Result { Ok(ExSeries::new(column.take_materialized_series())) } +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_unique(series: ExSeries) -> Result { + let unique = polars_ops::prelude::is_unique(&series.clone_inner())?; + Ok(ExSeries::new(unique.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_is_duplicated(series: ExSeries) -> Result { + let duplicated = polars_ops::prelude::is_duplicated(&series.clone_inner())?; + Ok(ExSeries::new(duplicated.into_series())) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_diff( + series: ExSeries, + n: i64, + null_behavior: ExNullBehavior, +) -> Result { + let diffed = polars_ops::prelude::diff(&series.clone_inner(), n, null_behavior.into())?; + Ok(ExSeries::new(diffed)) +} + +#[rustler::nif(schedule = "DirtyCpu")] +pub fn s_sign(s: ExSeries) -> Result { + if is_numeric(s.dtype()) { + let series = s + .clone_inner() + .into_frame() + .lazy() + .select([col(s.name().clone()).sign()]) + .collect()? + .column(s.name())? + .as_materialized_series() + .clone(); + + Ok(ExSeries::new(series)) + } else { + panic!("sign/1 not implemented for {:?}", &s.dtype()) + } +} + #[rustler::nif(schedule = "DirtyCpu")] pub fn s_count_matches( s1: ExSeries, diff --git a/test/explorer/series_test.exs b/test/explorer/series_test.exs index 461e28493..9bb55fdab 100644 --- a/test/explorer/series_test.exs +++ b/test/explorer/series_test.exs @@ -6812,6 +6812,265 @@ defmodule Explorer.SeriesTest do end end + describe "is_unique/1 and is_duplicated/1" do + test "should work with basic data types" do + data_types = [ + {:string, ["a", "b", "b", "c"], [true, false, false, true]}, + {:integer, [1, 2, 2, 3], [true, false, false, true]}, + {:boolean, [true, true, false], [false, false, true]}, + {:date, [~D[2024-01-01], ~D[2024-01-01], ~D[2025-01-01]], [false, false, true]}, + {:category, ["a", "a", "b"], [false, false, true]}, + {:u8, [1, 2, 2, 3], [true, false, false, true]} + ] + + Enum.each(data_types, fn {dtype, input, expected_output} -> + s = Series.from_list(input, dtype: dtype) + + unique = Series.is_unique(s) + assert Series.dtype(unique) == :boolean + assert Series.to_list(unique) == expected_output + + duplicated = Series.is_duplicated(s) + assert Series.dtype(duplicated) == :boolean + assert Series.to_list(duplicated) == Enum.map(expected_output, &Kernel.not(&1)) + end) + end + + test "should treat nil as a value" do + s = Series.from_list(["a", nil, "b", nil]) + + assert Series.to_list(Series.is_unique(s)) == [true, false, true, false] + assert Series.to_list(Series.is_duplicated(s)) == [false, true, false, true] + end + + test "should work with an empty series" do + s = Series.from_list([], dtype: :integer) + + assert Series.to_list(Series.is_unique(s)) == [] + assert Series.to_list(Series.is_duplicated(s)) == [] + end + + test "should work inside a filter" do + df = DataFrame.new(id: ["a", "b", "a", "c"]) + + assert DataFrame.filter_with(df, fn ldf -> Series.is_duplicated(ldf["id"]) end) + |> DataFrame.to_columns(atom_keys: true) == %{id: ["a", "a"]} + end + + test "should raise for unsupported dtypes" do + s = Series.from_list([[1, 2], [3]]) + + assert_raise ArgumentError, + ~r/Explorer\.Series\.is_unique\/1 not implemented/, + fn -> Series.is_unique(s) end + + assert_raise ArgumentError, + ~r/Explorer\.Series\.is_duplicated\/1 not implemented/, + fn -> Series.is_duplicated(s) end + end + end + + describe "sign/1" do + test "with signed integers" do + s = Series.from_list([-3, 0, 4]) + signs = Series.sign(s) + + assert Series.dtype(signs) == {:s, 64} + assert Series.to_list(signs) == [-1, 0, 1] + end + + test "with floats and nil" do + s = Series.from_list([-3.0, 0.0, 4.5, nil]) + signs = Series.sign(s) + + assert Series.dtype(signs) == {:f, 64} + assert Series.to_list(signs) == [-1.0, 0.0, 1.0, nil] + end + + test "keeps the dtype of the input series" do + s = Series.from_list([0, 5], dtype: :u8) + signs = Series.sign(s) + + assert Series.dtype(signs) == {:u, 8} + assert Series.to_list(signs) == [0, 1] + end + + test "should raise for unsupported dtypes" do + s = Series.from_list(["a", "b"]) + + assert_raise ArgumentError, + ~r/Explorer\.Series\.sign\/1 not implemented for dtype :string/, + fn -> Series.sign(s) end + end + end + + describe "diff/2" do + test "with the default options" do + s = Series.from_list([1, 3, 6, 10]) + diffed = Series.diff(s) + + assert Series.dtype(diffed) == {:s, 64} + assert Series.to_list(diffed) == [nil, 2, 3, 4] + end + + test "with a custom :n" do + s = Series.from_list([1, 3, 6, 10]) + + assert Series.to_list(Series.diff(s, n: 2)) == [nil, nil, 5, 7] + end + + test "with a negative :n looks forward" do + s = Series.from_list([1, 3, 6, 10]) + + assert Series.to_list(Series.diff(s, n: -1)) == [-2, -3, -4, nil] + end + + test "with null_behavior: :drop" do + s = Series.from_list([1, 3, 6, 10]) + diffed = Series.diff(s, null_behavior: :drop) + + assert Series.size(diffed) == 3 + assert Series.to_list(diffed) == [2, 3, 4] + end + + test "widens unsigned integers to signed integers" do + for {dtype, expected_dtype} <- [ + {:u8, {:s, 16}}, + {:u16, {:s, 32}}, + {:u32, {:s, 64}}, + {:u64, {:s, 64}} + ] do + s = Series.from_list([1, 3, 6], dtype: dtype) + diffed = Series.diff(s) + + assert Series.dtype(diffed) == expected_dtype + assert Series.to_list(diffed) == [nil, 2, 3] + end + end + + test "returns a duration for temporal dtypes" do + dates = Series.from_list([~D[2024-01-01], ~D[2024-01-03]]) + assert Series.dtype(Series.diff(dates)) == {:duration, :microsecond} + + times = Series.from_list([~T[00:00:00.000000], ~T[00:00:01.000000]]) + assert Series.dtype(Series.diff(times)) == {:duration, :nanosecond} + + datetimes = + Series.from_list( + [~N[2024-01-01 00:00:00.0], ~N[2024-01-01 00:00:01.0]], + dtype: {:naive_datetime, :millisecond} + ) + + assert Series.dtype(Series.diff(datetimes)) == {:duration, :millisecond} + end + + test "should work inside a mutation" do + df = DataFrame.new(a: [1, 3, 6, 10]) + + assert DataFrame.mutate_with(df, fn ldf -> [delta: Series.diff(ldf["a"])] end) + |> DataFrame.to_columns(atom_keys: true) == %{ + a: [1, 3, 6, 10], + delta: [nil, 2, 3, 4] + } + end + + test "should raise for an invalid :null_behavior" do + s = Series.from_list([1, 2, 3]) + + assert_raise ArgumentError, + "expected :null_behavior to be :ignore or :drop, got: :boom", + fn -> Series.diff(s, null_behavior: :boom) end + end + + test "should raise for unsupported dtypes" do + s = Series.from_list(["a", "b"]) + + assert_raise ArgumentError, + ~r/Explorer\.Series\.diff\/2 not implemented for dtype :string/, + fn -> Series.diff(s) end + end + end + + describe "kurtosis/2" do + test "with the default options" do + s = Series.from_list([1, 2, 3, 4, 5, 23]) + + assert Series.kurtosis(s) == 0.9945668771797536 + end + + test "with fisher: false" do + s = Series.from_list([1, 2, 3, 4, 5, 23]) + + assert Series.kurtosis(s, fisher: false) == 3.9945668771797536 + end + + test "with bias: false" do + s = Series.from_list([1, 2, 3, 4, 5, 23]) + + assert Series.kurtosis(s, bias: false) == 5.400820058440949 + end + + test "ignores nil values" do + s = Series.from_list([1, 2, 3, nil, 1]) + + assert Series.kurtosis(s) == -1.371900826446281 + end + + test "should raise for unsupported dtypes" do + s = Series.from_list(["a", "b"]) + + assert_raise ArgumentError, + ~r/Explorer\.Series\.kurtosis\/2 not implemented for dtype :string/, + fn -> Series.kurtosis(s) end + end + end + + describe "starts_with/2 and ends_with/2" do + test "detects literal prefixes and suffixes" do + s = Series.from_list(["abc", "def", "bcd"]) + + assert Series.to_list(Series.starts_with(s, "a")) == [true, false, false] + assert Series.to_list(Series.starts_with(s, "bc")) == [false, false, true] + assert Series.to_list(Series.ends_with(s, "d")) == [false, false, true] + assert Series.to_list(Series.ends_with(s, "bc")) == [true, false, false] + end + + test "propagates nil" do + s = Series.from_list(["abc", nil, "bcd"]) + + assert Series.to_list(Series.starts_with(s, "bc")) == [false, nil, true] + assert Series.to_list(Series.ends_with(s, "bc")) == [true, nil, false] + end + + test "treats the argument as a literal, not a pattern" do + s = Series.from_list(["a.c", "abc"]) + + assert Series.to_list(Series.starts_with(s, "a.")) == [true, false] + end + + test "should work inside a mutation" do + df = DataFrame.new(a: ["apple", "banana"]) + + assert DataFrame.mutate_with(df, fn ldf -> [flag: Series.starts_with(ldf["a"], "a")] end) + |> DataFrame.to_columns(atom_keys: true) == %{ + a: ["apple", "banana"], + flag: [true, false] + } + end + + test "should raise for unsupported dtypes" do + s = Series.from_list([1, 2]) + + assert_raise ArgumentError, + ~r/Explorer\.Series\.starts_with\/2 not implemented for dtype \{:s, 64\}/, + fn -> Series.starts_with(s, "a") end + + assert_raise ArgumentError, + ~r/Explorer\.Series\.ends_with\/2 not implemented for dtype \{:s, 64\}/, + fn -> Series.ends_with(s, "a") end + end + end + describe "peaks/1" do test "max with signed integers" do s = Series.from_list([1, 2, 4, 1, 4])