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

allow nils along with struct - from_list/2 #854

Merged
merged 3 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 10 additions & 4 deletions lib/explorer/polars_backend/shared.ex
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,16 @@ defmodule Explorer.PolarsBackend.Shared do
columns = Map.new(fields, fn {k, _v} -> {k, []} end)

columns =
Enum.reduce(list, columns, fn row, columns ->
Enum.reduce(row, columns, fn {field, value}, columns ->
Map.update!(columns, field, &[value | &1])
end)
Enum.reduce(list, columns, fn
nil, columns ->
Enum.reduce(fields, columns, fn {field, _}, columns ->
Map.update!(columns, field, &[nil | &1])
end)

row, columns ->
Enum.reduce(row, columns, fn {field, value}, columns ->
Map.update!(columns, field, &[value | &1])
end)
end)

series =
Expand Down
18 changes: 11 additions & 7 deletions lib/explorer/shared.ex
Original file line number Diff line number Diff line change
Expand Up @@ -387,13 +387,17 @@ defmodule Explorer.Shared do
Downcasts lists of mixed numeric types (float and int) to float.
"""
def cast_series(list, {:struct, dtypes}) when is_list(list) do
Enum.map(list, fn item ->
Enum.map(item, fn {field, inner_value} ->
column = to_string(field)
{^column, inner_dtype} = List.keyfind!(dtypes, column, 0)
[casted_value] = cast_series([inner_value], inner_dtype)
{column, casted_value}
end)
Enum.map(list, fn
nil ->
nil

item ->
Enum.map(item, fn {field, inner_value} ->
column = to_string(field)
{^column, inner_dtype} = List.keyfind!(dtypes, column, 0)
[casted_value] = cast_series([inner_value], inner_dtype)
{column, casted_value}
end)
end)
end

Expand Down
11 changes: 11 additions & 0 deletions test/explorer/series/struct_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ defmodule Explorer.Series.StructTest do
]
end

test "allow nils" do
s = Series.from_list([nil, %{"a" => 1, "b" => 2}, nil])
assert s.dtype == {:struct, [{"a", {:s, 64}}, {"b", {:s, 64}}]}

assert Series.to_list(s) == [
%{"a" => nil, "b" => nil},
%{"a" => 1, "b" => 2},
%{"a" => nil, "b" => nil}
]
lkarthee marked this conversation as resolved.
Show resolved Hide resolved
end

test "allows struct values" do
s = Series.from_list([%{a: 1}, %{a: 3}, %{a: 5}])

Expand Down
Loading