Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix from_list/2 of list of structs when first is empty #849

Merged
merged 2 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/explorer/polars_backend/shared.ex
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ defmodule Explorer.PolarsBackend.Shared do
Native.s_from_list_of_series(name, series)
end

def from_list(list, {:struct, fields} = _dtype, name) when is_list(list) do
def from_list(list, {:struct, fields} = dtype, name) when is_list(list) do
series =
for {column, values} <- Table.to_columns(list) do
column = to_string(column)
Expand All @@ -135,6 +135,14 @@ defmodule Explorer.PolarsBackend.Shared do
end

Native.s_from_list_of_series_as_structs(name, series)
|> then(fn polars_series ->
if Native.s_dtype(polars_series) != dtype do
{:ok, casted} = Native.s_cast(polars_series, dtype)
casted
else
polars_series
end
end)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to give a context, the problem was because the "empty" inner struct series were getting a different dtype, because it couldn't be "inferred" from the series alone (since it was empty).
The cast will force those empty struct series to keep the same dtype.

end

def from_list(list, dtype, name) when is_list(list) do
Expand Down
16 changes: 16 additions & 0 deletions test/explorer/series/list_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,22 @@ defmodule Explorer.Series.ListTest do
"the value \"z\" does not match the inferred dtype {:s, 64}",
fn -> Series.from_list([[[[[1, 2], ["z", "b"]]]]]) end
end

test "list of structs" do
series =
Series.from_list([[%{"a" => 42}], []], dtype: {:list, {:struct, %{"a" => :integer}}})

assert Series.dtype(series) == {:list, {:struct, %{"a" => {:s, 64}}}}
assert Series.to_list(Series.cast(series, Series.dtype(series))) == [[%{"a" => 42}], []]
philss marked this conversation as resolved.
Show resolved Hide resolved
end

test "list of structs with first empty" do
series =
Series.from_list([[], [%{"a" => 42}], []], dtype: {:list, {:struct, %{"a" => :integer}}})

assert Series.dtype(series) == {:list, {:struct, %{"a" => {:s, 64}}}}
assert Series.to_list(series) == [[], [%{"a" => 42}], []]
end
end

describe "cast/2" do
Expand Down
Loading