toodle

toodle

Dynamic column selection for Explorer dataframe

I’d like to query an Explorer DataFrame containing a “select” column such that the output gives, for each row, the field/column that was pointed to by the “select” column. Example:

iex>DF.print(my_df)
+--------------------------------------------+
| Explorer DataFrame: [rows: 3, columns: 3]  |
+--------------+--------------+--------------+
|     col1     |     col2     |    select    |
|   <string>   |   <string>   |   <string>   |
+==============+==============+==============+
| a            | b            | col1         |
+--------------+--------------+--------------+
| c            | d            | col2         |
+--------------+--------------+--------------+
| e            | f            | col2         |
+--------------+--------------+--------------+

The output I want is:

#Explorer.Series<
  Polars[3]
  string ["a", "d", "f"]
>

This pops up while processing categorical data and is related to a use-case involving one-hot encoding that was discussed here.

I was hoping to be able to use syntax that is fairly short, something like

my_df[.., my_df["select"]]

…but I haven’t been able to get that working yet. What I have gotten working is:

defmodule Janky do
  def dynamic_select(dataframe) do
    # use mutate_with combined with Series.select
    DF.mutate_with(dataframe, fn df ->
      [selection: 
          Enum.reduce(
            Enum.reject(dataframe.names, fn x -> x == "select" end),
            "nil",
            fn x, acc ->
              this_column = S.equal(df["select"], x)
              S.select(this_column, df[x], acc)
            end
          )
      ]
    end)
    |> DF.pull("selection")
  end
end

iex> Janky.dynamic_select(my_df)
#Explorer.Series<
  Polars[3]
  string ["a", "d", "f"]
>

This seems like a lot of code to do something fairly straightforward—is there anything more sleek built into Explorer?

In Pandas, there used to be DataFrame.lookup(), which I guess has been replaced by something slightly more verbose. I feel like this type of dynamic selection is supported by dplyr too…

Anything built into Explorer (or on the roadmap) for this?

First Post!

billylanchantin

billylanchantin

For the two-column example, there’s this:

df["select"] |> S.equal("col1") |> S.select(df["col1"], df["col2"])

To generalize, this works:

Enum.reduce(df.names -- ["select"], df["select"], fn col, acc ->
  df["select"] |> S.equal(col) |> S.select(df[col], acc)
end)

It’s very close what you had. The overall approach does seem a bit wasteful – I’d love to do things lazily. But I tried a few other ideas and didn’t get anywhere.

As for the roadmap, I think exposing some fold-based expressions may help here:

Last Post!

toodle

toodle

Ah, I see, so without mutate_with, pretty much. Nice! that is a bit tidier, thanks! Unfortunately, as you mentioned, it does remove the ability to do things lazily.

Even on eager frames, I’m seeing that mutate_with makes things 3-4x faster, kind of interersting.

r.e. fold, that seems very relevant, although it appears like it requires pretty much the same amount of code as this example uses. I’m thinking more tight function calls (that maybe wrap fold or what we’ve written here). Seems like a type of horizontal aggregation, which maybe it’d be helpful for Explorer to have a small number of. Polars issue tracking horizontal aggregations.

Where Next?

Popular in Questions Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement